Tkinter教程之 Label & Button 标签和按钮
from tkinter import *#引入tkinter所有功能 master = Tk()#创建窗口主体 master.title("TkinterSimple")#主体窗口的名称 #窗口大小 width ,height=300, 300 #窗口居中显示 master.geometry('%dx%d+%d+%d' % (width,height,(master.winfo_screenwidth() - width ) / 2, (master.winfo_screenheight() - height) / 2)) #窗口最大值 master.maxsize(300,300) #窗口最小值 master.minsize(300,300) #标签Label label = Label(master, text = 'Hello Tkinter',#标签显示文本 bitmap = 'info',#显示位图 bg='red', fg='#FF00FF', width=100, height=20, compound = 'left', ) label.pack() ''' 1.在label上使用内置位图 bitmap的使用方法 * error * hourglass * info * questhead * question * warning * gray12 * gray25 * gray50 * gray75 2.改变控件的前景色和背景色 fg:前景色 bg:背景色 3.设置宽度与高度 width: 宽度 height: 高度 4.时使用图像与文本 compound: 指定文本(text)与图像(bitmap/image)是如何在Label上显示,缺省为None, 当指定image/bitmap时,文本(text)将被覆盖,只显示图像了。可以使用的值: left: 图像居左 right: 图像居右 top: 图像居上 bottom:图像居下 center:文字覆盖在图像上 bitmap/image: 显示在Label上的图像 text: 显示在Label上的文本 5.文本的多行显示 在Tk004中,使用width和heigth来指定控件的大小,如果指定的大小无法满足文本的要求是,会出现 什么现象呢?如下代码: Label(root,bg = 'welcome to jcodeer.cublog.cn',width = 10,height = 3).pack() 运行程序,超出Label的那部分文本被截断了,常用的方法是:使用自动换行功能,及当文本长度大于 控件的宽度时,文本应该换到下一行显示,Tk不会自动处理,但提供了属性: wraplength: 指定多少单位后开始换行 justify: 指定多行的对齐方式 ahchor: 指定文本(text)或图像(bitmap/image)在Label中的显示位置 可用的值: e w n s ne se sw sn center 布局如下图 nw n ne w center e sw s se justify与anchor的区别了:一个用于控制多行的对齐;另一个用于 控制整个文本块在Label中的位置 6. ''' #按钮Button def callback(): print('click!') b.configure(width=30, height=3)#重新设置宽高 b.configure(var.set('hello!'))#变量设置 b.configure(state='disable') var = StringVar() b = Button(master, text="Button", command=callback,#按钮动作执行动作 width=15, height=2, bg='yellow',#背景色 fg='green',#前景色 anchor='s',#文本在控件上的位置 bd='2',#边框 relief='ridge', state ='normal', textvariable = var#变量传值 ) ''' 1.设置宽高 1 b.configure(width = 30,height = 3) 2 b2['width'] = 30 b2['height'] = 3 2.设置Button文本在控件上的显示位置 anchor: 使用的值为:n(north),s(south),w(west),e(east)和ne,nw,se,sw,center 局中,就是地图上的标识位置了,使用 width和height属性是为了显示各个属性的不同 3.改变Button的前景色与背景色 fg:前景色 bg:背景色 4.设置Button的边框 bd(bordwidth):缺省为1或2个像素 5.设置Button的风格 relief:raised/sunken/groove/ridge 6.设置Button状态 normal/active/disabled 7.绑定Button与变量 设置Button在textvariable属性 ''' b.pack() master.mainloop()#窗口事件循环
运行结果:
评论