• 输入框的基本使用 ```python import tkinter as tk

window = tk.Tk()

设置窗口标题

window.title(‘my window’) window.geometry(‘400x300’)

一个输入框

e = tk.Entry(window, show=None) e.pack()

def insert_point(): var = e.get()

  1. # 在指针处插入
  2. t.insert('insert', var)

def insert_end(): var = e.get()

  1. # 在文本末尾插入
  2. t.insert('end', var)

按钮

b = tk.Button(window, text=’insert point’, width=15, height=2, command=insert_point) b1 = tk.Button(window, text=’insert end’, width=15, height=2, command=insert_end)

将组件在指定位置排列显示

b.pack() b1.pack()

多行文本框

t = tk.Text(window, height=2) t.pack()

循环显示窗口

window.mainloop()

  1. - 文本框的基本使用
  2. ```python
  3. import tkinter as tk
  4. import webbrowser
  5. from tkinter import messagebox
  6. class Application(tk.Frame):
  7. def __init__(self, master=None):
  8. # 绑定主画布
  9. super().__init__(master)
  10. self.master = master
  11. self.pack()
  12. self.createWidget()
  13. # 创建组件
  14. def createWidget(self):
  15. self.b1 = tk.Button(self, {
  16. 'text': '在光标处插入文本',
  17. 'command': self.addT1,
  18. }).pack(side="left")
  19. self.b2 = tk.Button(self, {
  20. 'text': '在文本末尾插入文本',
  21. 'command': self.addT2,
  22. }).pack(side="left")
  23. self.b3 = tk.Button(self, {
  24. 'text': '插入图片',
  25. 'command': self.addImg
  26. }).pack(side="left")
  27. self.b2 = tk.Button(self, {
  28. 'text': '在文本末尾插入组件',
  29. 'command': self.addWidget,
  30. }).pack(side="left")
  31. self.b2 = tk.Button(self, {
  32. 'text': 'tag',
  33. 'command': self.tag,
  34. }).pack(side="left")
  35. self.t1 = tk.Text(self, {
  36. 'width': 40,
  37. 'height': 12,
  38. 'bg': '#CCCCCC',
  39. 'fg': '#000000',
  40. })
  41. self.t1.pack()
  42. self.t1.insert(0.0, '插入文本\n')
  43. self.t1.insert(1.2, 'aaa\n')
  44. # 在光标处插入文本
  45. def addT1(self):
  46. self.t1.insert('insert', '在光标处插入文本')
  47. # 在文本末尾插入文本
  48. def addT2(self):
  49. self.t1.insert('end', '在文本末尾插入文本')
  50. def addImg(self):
  51. self.imgFile = tk.PhotoImage(file="img/1.GIF")
  52. self.t1.image_create('end', image=self.imgFile)
  53. def addWidget(self):
  54. self.b2 = tk.Button(self.t1, {
  55. 'text': '插入的按钮'
  56. })
  57. self.t1.window_create('end', window=self.b2)
  58. def tag(self):
  59. # 清空文本框
  60. self.t1.delete(1.0, 'end')
  61. # 新的文本
  62. self.t1.insert(1.0, 'new text good')
  63. # 标记一个带操作的文本
  64. self.t1.tag_add('tag1', 1.0, 1.3)
  65. # 设置 tag 添加的文本属性
  66. self.t1.tag_config('good', {
  67. 'background': 'yellow',
  68. 'foreground': 'red'
  69. })
  70. # 一个有事件的文本
  71. self.t1.tag_add('tag2', 1.0, 1.3)
  72. # 添加下划线
  73. self.t1.tag_config('tag2', underline=True)
  74. self.t1.tag_bind('tag2', "<Button-1>", self.goBaidu)
  75. def goBaidu(self, e):
  76. webbrowser.open('https://www.baidu.com')
  77. # 窗口主体
  78. root = tk.Tk()
  79. root.geometry("600x300+500+300")
  80. root.title('GUI 测试')
  81. # 子窗口
  82. app = Application(master=root)
  83. root.mainloop()