一个小例子
from tkinter import *
from tkinter import messagebox
def print_hi(name):
print(f'Hi, {name}') # Press Ctrl+F8 to toggle the breakpoint.
def songhua(e): # e就是事件对象
messagebox.showinfo("Message", "送你一朵玫瑰花,亲亲我吧")
print("送你99朵玫现花")
# Press the green button in the gutter to run the script.
if __name__ == '__main__':
print_hi('PyCharm')
root = Tk()
root.title("我的第一个GUI程序")
root.geometry("500x300+100+200")
btn1 = Button(root)
btn1["text"] = "点我就送花"
btn1.pack()
btn1.bind("<Button-1>", songhua)
root.mainloop() # 调用组件的mainloop方法,进入事件循环
python gui组件
- Misc和 Wm
Tkinter的GUI组件有两个根父类,它们都直接继承了object类: - Misc
它是所有组件的根父类。 - Wm
它主要提供了一些与窗口管理器通信的功能函数。 - Tk
Misc和 Wm派生出子类Tk,它代表应用程序的主窗口,一般应用程序都需要直接或间接使用Tk。 - Pack、 Place、 Grid
Pack、Place、Grid是布局管理器。布局管理器管理组件的:大小、位置.通过布局管理器可以将容器中的组件实现合理的排布. - BaseWidget
BaseWidget是所有组件的父类 - widget
Widget是所有组件类的父类。Widget一共有四个父类: BaseWidget、Pack、Grid、Place。意味着,所有GUI组件同时具备这四个父类的属性和方法。
常用组件
面向对象的写法
通过类Application组织整个GUI程序。类Application继承了Frame及通过继承拥有了父类的特性。通过构造函数_init_()初始化窗口中的对象。通过createWidgets()方法创建窗口中的对象。
Frame框架是一个tkinter组件,表示一个矩形的区域。Frame一般作为容器使用,可以放置其他组件,从而实现复杂的布局。
官方例子
https://docs.python.org/3.7/library/tkinter.html
import tkinter as tk
class Application(tk.Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.create_widgets()
def create_widgets(self):
self.hi_there = tk.Button(self)
self.hi_there["text"] = "Hello World\n(click me)"
self.hi_there["command"] = self.say_hi
self.hi_there.pack(side="top")
self.quit = tk.Button(self, text="QUIT", fg="red",
command=self.master.destroy)
self.quit.pack(side="bottom")
def say_hi(self):
print("hi there, everyone!")
root = tk.Tk()
app = Application(master=root)
app.mainloop()
自己的例子
from tkinter import *
from tkinter import messagebox
class Application(Frame):
def __init__( self, master=None):
super().__init__(master) # 调用父类构造器 super()代表的是父类的定义,而不是父类对象
self.master = master
self.pack()
self.createwidget()
def createwidget(self):
self.btn01 = Button(self)
self.btn01["text"]="点击送花"
self.btn01.pack()
self.btn01["command"] = self.songhua
# 创建一个退出按钮
self.btnQuit = Button(self, text="退出",command = root.destroy)
self.btnQuit.pack()
def songhua(self):
messagebox.showinfo("送花","送你99朵玫瑰花")
root=Tk()
root.geometry("400x100+200+300")
root.title("一个经典的GUI程序类的测试")
app = Application(master=root)
root.mainloop()
文件对话框
文件对话框帮助我们实现可视化的操作目录、操作文件。最后,将文件、目录的信息传入到程序中。文件对话框包含如下一些常用函数:
Label标签
Label(标签)主要用于显示文本信息,也可以显示图像。
Label (标签)有这样一些常见属性:
- width,height:
用于指定区域大小,如果显示是文本,则以单个英文字符大小为单位(一个汉字宽度占2个字符位置,高度和英文字符一弟;如果显示是图像,则以像素为单位。默认值是根据具体显示的内容动态调整。 - font
指定字体和字体大小,如: font = (font_name,size) - image:
显示在Label上的图像,目前tkinter只支持gif格式. - fg 和 bg
fg (foreground):前景色、bg (background):背景色 - justify
针对多行文字的对齐,可设置justify属性,可选值"left",“center” or “right”
pack布局管理器
pack按照组件的创建顺序将子组件添加到父组件中,按照垂直或者水平的方向自然排布。如果不指定任何选项,默认在父组件中自顶向下垂直添加组件。
pack是代码量最少,最简单的一种,可以用于快速生成界面.
pack适用于简单的垂直或水平排布,如果需要复杂的布局可以使用grid 或place。