Label (文本与图片)
import tkinter as tkfrom tkinter import messageboxclass Application(tk.Frame):def __init__(self, master=None):# 绑定主画布super().__init__(master)self.master = masterself.pack()self.createWidget()# 创建组件def createWidget(self):self.l1 = tk.Label(self, {'text': 'DEMO LABEL','width': 10,'height': 5,'bg': 'black','fg': 'white',})self.l1.pack()self.photoImg = tk.PhotoImage(file='img/1.GIF')self.p1 = tk.Label(self, {'image': self.photoImg,})self.p1.pack()# lable# 窗口主体root = tk.Tk()root.geometry("600x300+500+300")root.title('GUI 测试')# 子窗口app = Application(master=root)root.mainloop()
(以下文档来源于网路, 学习参考使用)
文档 1.pdf
单行文本框
import tkinter as tkfrom tkinter import messageboxclass Application(tk.Frame):def __init__(self, master=None):# 绑定主画布super().__init__(master)self.master = masterself.pack()self.createWidget()# 创建组件def createWidget(self):self.l1 = tk.Label(self, {'text': '用户名',})self.v1 = tk.StringVar(self, 'admin')self.e1 = tk.Entry(self, {'textvariable': self.v1})self.l2 = tk.Label(self, {'text': '密码',})self.v2 = tk.StringVar(self, '123456')self.e2 = tk.Entry(self, {'textvariable': self.v2})self.b1 = tk.Button(self, {'text': '登录','command': self.login})self.l1.pack()self.e1.pack()self.l2.pack()self.e2.pack()self.b1.pack()def login(self):username = self.v1.get()password = self.v2.get()if username == 'admin' and password == '123456':messagebox.showinfo('提醒', '登录成功!')else:messagebox.showerror('错误', '用户名或密码错误!')# 窗口主体root = tk.Tk()root.geometry("600x300+500+300")root.title('GUI 测试')# 子窗口app = Application(master=root)root.mainloop()
画布
import tkinter as tkimport webbrowserfrom tkinter import messageboxclass Application(tk.Frame):def __init__(self, master=None):# 绑定主画布super().__init__(master)self.master = masterself.pack()self.createWidget()# 创建组件def createWidget(self):self.canvas = tk.Canvas(self, {'width': 300,'height': 200,})self.canvas.pack()# 直线# 从画布左上角开始计算的, x0,y0,x1,y1,...self.canvas.create_line(0, 0, 10, 10)# 矩形self.canvas.create_rectangle(10, 20, 80, 80)# 窗口主体root = tk.Tk()root.geometry("600x300+500+300")root.title('GUI 测试')# 子窗口app = Application(master=root)root.mainloop()
