1、# Tkinter 教程之 Button 篇(2)5.指定 Button 的宽度与高度width: 宽度heigth: 高度使用三种方式:1.创建 Button 对象时,指定宽度与高度2.使用属性 width 和 height 来指定宽度与高度3.使用 configure 方法来指定宽度与高度from Tkinter import *root = Tk()b1 = Button(root,text = 30X1,width = 30,height = 2)b1.pack()b2 = Button(root,text = 30X2)b2width = 30b2height = 3b2.pack(
2、)b3 = Button(root,text = 30X3)b3.configure(width = 30,height = 3)b3.pack()root.mainloop()# 上述的三种方法同样也适合其他的控件6.设置 Button 文本在控件上的显示位置anchor:使用的值为:n(north),s(south),w(west),e(east)和 ne,nw,se,sw,就是地图上的标识位置了,使用width 和 height 属性是为了显示各个属性的不同。from Tkinter import *root = Tk()#简单就是美!for a in n,s,e,w,ne,nw,se,
3、sw:Button(root,text = anchor,anchor = a,width = 30,height = 4).pack()#如果看的不习惯,就使用下面的代码。# Button(root,text = anchor,width = 30,height =4).pack()# Button(root,text = anchor,anchor = center,width = 30,height =4).pack()# Button(root,text = anchor,anchor = n,width = 30,height = 4).pack()# Button(root,tex
4、t = anchor,anchor = s,width = 30,height = 4).pack()# Button(root,text = anchor,anchor = e,width = 30,height = 4).pack()# Button(root,text = anchor,anchor = w,width = 30,height = 4).pack()# Button(root,text = anchor,anchor = ne,width = 30,height = 4).pack()# Button(root,text = anchor,anchor = nw,widt
5、h = 30,height = 4).pack()# Button(root,text = anchor,anchor = se,width = 30,height = 4).pack()# Button(root,text = anchor,anchor = sw,width = 30,height = 4).pack()root.mainloop()7.改变 Button 的前景色与背景色fg: 前景色bg:背景色from Tkinter import *root = Tk()bfg = Button(root,text = change foreground,fg = red)bfg.p
6、ack()bbg = Button(root,text = change backgroud,bg = blue)bbg.pack()root.mainloop()8.设置 Button 的边框bd(bordwidth):缺省为 1 或 2 个像素# 创建 5 个 Button 边框宽度依次为: 0,2,4,6,8from Tkinter import *root = Tk()for b in 0,1,2,3,4:Button(root,text = string(b),bd = b).pack()root.mainloop() 9.设置 Button 的风格relief/raised/sun
7、ken/groove/ridgefrom Tkinter import *root = Tk()for r in raised,sunken,groove,ridge:Button(root,text = r,relief = r,width = 30).pack()root.mainloop()10.设置 Button 状态normal/active/disabledfrom Tkinter import *root = Tk()def statePrint():print statefor r in normal,active,disabled:Button(root,text = r,s
8、tate = r,width = 30,command = statePrint).pack()root.mainloop()#例子中将三个 Button 在回调函数都设置为 statePrint,运行程序只有 normal 和 active 激活了回调函数,而 disable 按钮则没有,对于暂时不#需要按钮起作用时,可以将它的 state 设置为 disabled 属性11.绑定 Button 与变量设置 Button 在 textvariable 属性from Tkinter import *root = Tk()def changeText():if btext = text:v.set(change)print changeelse:v.set(text)print textv = StringVar()b = Button(root,textvariable = v,command = changeText)v.set(text)b.pack()root.mainloop()将变量 v 与 Button 绑定,当 v 值变化时,Button 显示的文本也随之变化