Skip to main content
 首页 » 编程设计

python之Tkinter之使用按钮编辑文本框

2025年05月04日15zlslch

在 Python 中使用 Tkinter 我试图更改按下按钮时文本框中显示的内容。到目前为止我的代码是:

screen = Tk() 
text = Text(screen, height = 2, width = 30) 
text.pack() 
text.insert(END, '-') 
 
def apress(): 
    text.insert(END, 'a') 
 
a = Tkinter.Button (screen, text = 'a', width = 5, command = apress).pack() 
 
mainloop() 

当代码运行时,没有任何反应,即使您单击“中止调试”,调试器也不会停止运行。有没有办法来解决这个问题?

请您参考如下方法:

这是工作代码:

from Tkinter import * 
 
screen = Tk() 
text = Text(screen, height = 2, width = 30) 
text.pack() 
text.insert(END, '-') 
 
def apress(): 
    text.insert(END, 'a') 
 
btn = Button(screen, text = 'a', width = 5, command = apress)  
btn.pack() 
 
mainloop() 

我所做的更改:

  • 添加了导入 from Tkinter import *
  • 使用 Button 而不是 Tkinter.Button - 因为我们使用了通配符导入
  • Button.pack() 换行分隔

演示:

初始 View :

多次点击按钮: