from tkinter import *
from tkinter import messagebox
from PIL import Image, ImageTk
class Application(Frame):
def __init__(self, master=None):
super().__init__(master)
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
# 创建label
self.label1 = Label(self, text='label-test', width=10, height=2, bg='black', fg='white', font=('黑体', 10))
self.label1.pack()
# 显示图像
global img # 将 img 声明为全局变量,如果是局部变量的话本方法执行完毕之后图像对象会销毁,窗口显示不出来图像
img = ImageTk.PhotoImage(file="./imgs/p1.png") # 需要使用ImageTk, 正常只能显示gif格式图像,导入PIL之后可以使用其他格式的图像
self.label2 = Label(self, image=img)
self.label2.pack()
# 显示多行文本
self.label3 = Label(self, text='第一行\n第二行内容\n第三行', borderwidth=1, relief='solid', justify='left')
self.label3.pack()
# 创建按钮
self.btn1 = Button(self)
self.btn1['text'] = '按钮1'
self.btn1.pack()
self.btn1['command'] = self.btn1_event
# self.btn1.config(state='disabled') # 设置按钮为禁用
#创建一个退出按钮
self.btnQuit = Button(self, text='退出', command=root.destroy)
self.btnQuit.pack()
# 按钮点击事件
def btn1_event(self):
messagebox.showinfo('弹窗test', '弹窗信息')
if __name__ == '__main__':
root = Tk()
root.geometry('400x300+200+300') #此处x为小写字母, 宽 高 左边距 右边距
root.title('hello GUI')
app = Application(master=root)
root.mainloop()
效果图: