【问题标题】:Tkinter - editing a text box using a buttonTkinter - 使用按钮编辑文本框
【发布时间】:2016-04-07 08:07:36
【问题描述】:

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

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

【问题讨论】:

  • 如果我错了,请纠正我,但Text 字段不应该有一个StringVar
  • 注意缩进。
  • 我添加了from Tkinter import * 并删除了a = Tkinter.,您的代码对我有用。 Linux Mint 17,Python 2.7.11。
  • 顺便说一句:a = Button(...).pack()None 分配给a,因为pack() 返回None。如果不需要a,请使用a = Button(...) ; a.pack()Button(...).pack()
  • @MalikBrahimi:不,你不需要在任何地方使用StringVar

标签: python python-2.7 tkinter


【解决方案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() 换行

演示:

初始视图:

多次点击按钮:

【讨论】:

  • 感谢您的帮助!按下按钮时是否可以替换屏幕上的文本?
  • 这有点棘手 - 使用 text.delete() 然后 text.insert()
猜你喜欢
  • 2019-01-08
  • 1970-01-01
  • 2021-10-09
  • 2020-07-22
  • 2019-05-25
  • 2015-07-21
  • 1970-01-01
  • 2023-04-07
  • 1970-01-01
相关资源
最近更新 更多