1、 from tkinter import Label widget=Label(None,text='Hello Gui') widget.pack() widget.mainloop() 2| expand fill:组件随窗口调整大小 from tkinter import * widget=Label(None,text='Hello Gui') widget.pack(expand=YES,fill=BOTH) widget.mainloop()
3、字典方式设置组件属性:
image.png
4、设置窗体标题
image.png
5、button
import sys
from tkinter import * w=Button(None,text="tetxxx",command=sys.exit) w.pack() w.mainloop() 6、root.quit,side=LEFT
image.png
7、自定义回调函数: import sys from tkinter import *
def quit(): # a custom callback handler print('Hello, I must be going...') # kill windows and process sys.exit()
widget = Button(None, text='Hello event world', command=quit) widget.pack() widget.mainloop() 8、类方法
image.png
9、绑定鼠标事件:<Button-1> <Double-1> bind import sys from tkinter import *
def hello(event): print('Press twice to exit') # on single-left click
def quit(event): # on double-left click print('Hello, I must be going...') # event gives widget, x/y, etc. sys.exit()
widget = Button(None, text='Hello event world') widget.pack() widget.bind('<Button-1>', hello) # bind left mouse clicks widget.bind('<Double-1>', quit) # bind double-left clicks widget.mainloop() 10、添加多个组件:Frame,Button,Label from tkinter import *
def greeting(): print('Hello stdout world!...')
win = Frame() win.pack(side=TOP, expand=YES, fill=BOTH) Button(win, text='Hello', command=greeting).pack(side=LEFT, fill=Y) Label(win, text='Hello container world').pack(side=TOP) Button(win, text='Quit', command=win.quit).pack(side=RIGHT, expand=YES,fill=X)
win.mainloop() 11、fill 当窗体扩大缩小时,也跟着扩大缩小 12、anchor属性,N,NE,NW,S东西南北 13、自定义button类:self.init self.__config from tkinter import *
class HelloButton(Button): def init(self, parent=None, **config): # add callback method Button.init(self, parent, **config) # and pack myself self.pack() # could config style too self.config(command=self.callback)
def callback(self): # default press action
print('Goodbye world...') # replace in subclasses
self.quit()
if name == 'main': HelloButton(text='Hello subclass world').mainloop()
13、self.config fg,bg,font,relief
image.png
14、frame重载 from tkinter import *
class Hello(Frame): # an extended Frame def init(self, parent=None): Frame.init(self, parent) # do superclass init self.pack() self.data = 42 self.make_widgets() # attach widgets to self
def make_widgets(self):
widget = Button(self, text='Hello frame world!', command=self.message)
widget.pack(side=LEFT)
def message(self):
self.data += 1
print('Hello frame world %s!' % self.data)
if name == 'main': Hello().mainloop() 15、Hello.widget() 父类和子类的方法都执行
image.png
16、tkinter组件类:
Label,Button,Frame,TK,Message,Entry,Checkbutton,Radiobutton,Scale,PhotoImage,BitmapImage,Menu,Menubutton,Scrollbar,Text,Canvas
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有