Label (文本与图片)

  1. import tkinter as tk
  2. from tkinter import messagebox
  3. class Application(tk.Frame):
  4. def __init__(self, master=None):
  5. # 绑定主画布
  6. super().__init__(master)
  7. self.master = master
  8. self.pack()
  9. self.createWidget()
  10. # 创建组件
  11. def createWidget(self):
  12. self.l1 = tk.Label(self, {
  13. 'text': 'DEMO LABEL',
  14. 'width': 10,
  15. 'height': 5,
  16. 'bg': 'black',
  17. 'fg': 'white',
  18. })
  19. self.l1.pack()
  20. self.photoImg = tk.PhotoImage(file='img/1.GIF')
  21. self.p1 = tk.Label(self, {
  22. 'image': self.photoImg,
  23. })
  24. self.p1.pack()
  25. # lable
  26. # 窗口主体
  27. root = tk.Tk()
  28. root.geometry("600x300+500+300")
  29. root.title('GUI 测试')
  30. # 子窗口
  31. app = Application(master=root)
  32. root.mainloop()

(以下文档来源于网路, 学习参考使用)
文档 1.pdf

单行文本框

  1. import tkinter as tk
  2. from tkinter import messagebox
  3. class Application(tk.Frame):
  4. def __init__(self, master=None):
  5. # 绑定主画布
  6. super().__init__(master)
  7. self.master = master
  8. self.pack()
  9. self.createWidget()
  10. # 创建组件
  11. def createWidget(self):
  12. self.l1 = tk.Label(self, {
  13. 'text': '用户名',
  14. })
  15. self.v1 = tk.StringVar(self, 'admin')
  16. self.e1 = tk.Entry(self, {
  17. 'textvariable': self.v1
  18. })
  19. self.l2 = tk.Label(self, {
  20. 'text': '密码',
  21. })
  22. self.v2 = tk.StringVar(self, '123456')
  23. self.e2 = tk.Entry(self, {
  24. 'textvariable': self.v2
  25. })
  26. self.b1 = tk.Button(self, {
  27. 'text': '登录',
  28. 'command': self.login
  29. })
  30. self.l1.pack()
  31. self.e1.pack()
  32. self.l2.pack()
  33. self.e2.pack()
  34. self.b1.pack()
  35. def login(self):
  36. username = self.v1.get()
  37. password = self.v2.get()
  38. if username == 'admin' and password == '123456':
  39. messagebox.showinfo('提醒', '登录成功!')
  40. else:
  41. messagebox.showerror('错误', '用户名或密码错误!')
  42. # 窗口主体
  43. root = tk.Tk()
  44. root.geometry("600x300+500+300")
  45. root.title('GUI 测试')
  46. # 子窗口
  47. app = Application(master=root)
  48. root.mainloop()

画布

  1. import tkinter as tk
  2. import webbrowser
  3. from tkinter import messagebox
  4. class Application(tk.Frame):
  5. def __init__(self, master=None):
  6. # 绑定主画布
  7. super().__init__(master)
  8. self.master = master
  9. self.pack()
  10. self.createWidget()
  11. # 创建组件
  12. def createWidget(self):
  13. self.canvas = tk.Canvas(self, {
  14. 'width': 300,
  15. 'height': 200,
  16. })
  17. self.canvas.pack()
  18. # 直线
  19. # 从画布左上角开始计算的, x0,y0,x1,y1,...
  20. self.canvas.create_line(0, 0, 10, 10)
  21. # 矩形
  22. self.canvas.create_rectangle(10, 20, 80, 80)
  23. # 窗口主体
  24. root = tk.Tk()
  25. root.geometry("600x300+500+300")
  26. root.title('GUI 测试')
  27. # 子窗口
  28. app = Application(master=root)
  29. root.mainloop()