python基础知识-GUI编程-TK-Button

1、最基础的用法

        其实和其他的TK组件的用法基本相同,建下面的代码行
      
root = Tkinter.TK()

ttk.Button(root, text="submit").grid()

root.mainloop()

        其中的text属性就是button的名称

2、绑定某个函数以进行数据 处理

def testClick():
    print "this is the testClick method"

root = Tkinter.TK()

ttk.Button(root, text = "submit", command = testClick).grid()

root.mainloop()

3、通过绑定事件来进行数据处理


def testClick():
print "this is the testClick method"

def testEvent(event):
print "this is the testEvent method"
print "the time of event is ", event.time

root = Tkinter.Tk()


b = ttk.Button(root, text="submit", command = testClick)
b.bind("<Return>", testEvent)
b.grid()

root.mainloop()

        和之前不一样的地方是,需要明确一个对象名称,以方便调用bind函数;另外,还有一个需要注意的地方是,bind函数的调用是在合入frame之前,也就是调用grid或者pack函数之前

4、点击Button处理数据成功后,弹出对话框

        弹出对话框的处理是使用tkMessageBox函数,代码如下:

import tkMessageBox


def testClick():
print "this is the testClick method"
        tkMessageBox.showeinfo(message = 'this method is success')


def testEvent(event):
print "this is the testEvent method"
print "the time of event is ", event.time

root = Tkinter.Tk()
root.geometry('400x150+400+200')
root.title("test")

b = ttk.Button(root, text="submit", command = testClick)
b.bind("<Return>", testEvent)
b.grid()

root.mainloop()

        这个tkMessageBox.showinfo函数显示了一个提示框,有一个确定按钮




        具体参考: http://www.tkdocs.com/tutorial/windows.html

5、较为复杂的对话框

        很多场景下需要使用较为复杂的对话框,例如:有一个确定和取消按钮。针对这些场景,tkMessageBox提供了如下的方法:
        askokcancel,  askyesno,  askyesnocancel,  askretrycancel,  askabortretryignore

        这些方法的特点是,当选择ok或者是yes的时候,返回值为true;这样就可以根据返回值做相应的处理动作。事例代码如下:


import tkMessageBox

def testClick():
print "this is the testClick method"
flag = tkMessageBox.askokcancel(message = "this is okcancel")

if flag == True:
  root.destroy()
elif flag == False:
  print "cancel"


def testEvent(event):
print "this is the testEvent method"
print "the time of event is ", event.time

root = Tkinter.Tk()
root.geometry('400x150+400+200')
root.title("test")

b = ttk.Button(root, text="submit", command = testClick)
b.bind("<Return>", testEvent)
b.grid()

root.mainloop()

你可能感兴趣的:(python,GUI,TK)