Tkinter - 使用按钮编辑文本框

时间:2016-01-03 16:31:12

标签: python python-2.7 tkinter

在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()

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

1 个答案:

答案 0 :(得分:1)

这是工作代码:

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()在新行上分开

演示:

初步观点: Before clicking button

多次点击该按钮:

After clicking button