from tkinter import * #定义Button的回调函数 def helloButton(): print ('hello button') root = Tk() #通过command属性来指定Button的回调函数 Button(root,text = 'Hello Button',command = helloButton).pack() root.mainloop()
from tkinter import * root = Tk() #flat, groove, raised, ridge, solid, or sunken Button(root,text = 'hello button',relief=FLAT).pack() Button(root,text = 'hello button',relief=GROOVE).pack() Button(root,text = 'hello button',relief=RAISED).pack() Button(root,text = 'hello button',relief=RIDGE).pack() Button(root,text = 'hello button',relief=SOLID).pack() Button(root,text = 'hello button',relief=SUNKEN).pack() root.mainloop()
from tkinter import * root = Tk() #图像居下,居上,居右,居左,文字位于图像之上 Button(root,text = 'botton',compound = 'bottom',bitmap = 'error').pack() Button(root,text = 'top',compound = 'top',bitmap = 'error').pack() Button(root,text = 'right',compound = 'right',bitmap = 'error').pack() Button(root,text = 'left',compound = 'left',bitmap = 'error').pack() Button(root,text = 'center',compound = 'center',bitmap = 'error').pack() root.mainloop()
from tkinter import * def cb1(): print ('button1 clicked') def cb2(event): print ('button2 clicked') def cb3(): print ('button3 clicked') root = Tk() b1 = Button(root,text = 'Button1',command = cb1) b2 = Button(root,text = 'Button2') b2.bind("<Return>",cb2) #Return事件相应回车点击。Enter事件响应的是mouseover b3 = Button(root,text = 'Button3',command = cb3) b1.pack() b2.pack() b3.pack() b2.focus_set() #将焦点定在按钮b2上 root.mainloop()上例中使用了bind方法,它建立事件与回调函数(响应函数)之间的关系,每当产生<Enter>事件后,程序便自动的调用cb2,与cb1,cb3不同的是,它本身还带有一个参数----event,这个参数传递响应事件的信息。
from tkinter import * root = Tk() b1 = Button(root,text = '30X1',width = 30,height = 2) b1.pack() b2 = Button(root,text = '30X2') b2['width'] = 30 b2['height'] = 3 b2.pack() b3 = Button(root,text = '30X3') b3.configure(width = 30,height = 3) b3.pack() root.mainloop()
from Tkinter import * root = Tk() #简单就是美! for a in ['n','s','e','w','ne','nw','se','sw']: Button(root, text = 'anchor', anchor = a, width = 30, height = 4).pack()
from tkinter import * root = Tk() bfg = Button(root,text = 'change foreground',fg = 'red') bfg.pack() bbg = Button(root,text = 'change backgroud',bg = 'blue') bbg.pack() root.mainloop()
# 创建5个Button边框宽度依次为:0,2,4,6,8 from tkinter import * root = Tk() for b in [0,1,2,3,4]: Button(root, text = str(b), bd = b).pack() root.mainloop()
from tkinter import * root = Tk() def statePrint(): print ('state') for r in ['normal','active','disabled']: Button(root, text = r, state = r, width = 30, command = statePrint).pack() root.mainloop()例子中将三个Button在回调函数都设置为statePrint,运行程序只有normal和active激活了回调函数,而disable按钮则没有,对于暂时不需要按钮起作用时,可以将它的state设置为disabled属性
from tkinter import * root = Tk() def changeText(): if b['text'] == 'text': v.set('change') else: v.set('text') v = StringVar() b = Button(root,textvariable = v,command = changeText) v.set('text') b.pack() root.mainloop()将变量v与Button绑定,当v值变化时,Button显示的文本也随之变化
原文:http://blog.csdn.net/a359680405/article/details/45071117