【问题标题】:Update a label in tkinter from a button press通过按下按钮更新 tkinter 中的标签
【发布时间】:2016-09-04 18:29:23
【问题描述】:

我的问题是关于使用 tkinter 在 python 中进行 GUI 编程。我相信这是 Python 3x。

我的问题:当我们执行程序来运行 GUI 时,按钮可以更新标签吗?更具体地说,有没有办法在按下按钮后更改标签显示的文本?我之前已经咨询过堆栈溢出并采用了 StringVar() 方法,但它似乎并没有解决我的问题,实际上它完全省略了 GUI 中的文本!

下面是代码

from tkinter import *

root = Tk()
root.title('Copy Text GUI Program')

copiedtext = StringVar()
copiedtext.set("Text is displayed here")


def copytext():
    copiedtext.set(textentered.get())

# Write 'Enter Text Here'
entertextLabel = Label(root, text="Enter Text Here")
entertextLabel.grid(row=0, column=0)

# For the user to write text into the gui
textentered = Entry(root)
textentered.grid(row=0, column=1)

# The Copy Text Button
copytextButton = Button(root, text="Copy Text")
copytextButton.grid(row=1, columnspan=2)

# Display the copied text
displaytextLabel = Label(root, textvariable=copiedtext)
displaytextLabel.grid(row=2,columnspan=2)


copytextButton.configure(command=copytext())

root.mainloop()

任何帮助将不胜感激!

【问题讨论】:

  • 作为对我的问题的修正,当我为 displaytextLabel 编写文本而不是 textvariable 时,它​​会输出一些 PY-4060(我认为这是内存,不确定)所以我知道这不是问题。

标签: python tkinter


【解决方案1】:

你要做的就是将一个 Button 事件绑定到 copytextButton 对象,如下所示:

copytextButton.bind('<Button-1>', copytext)

这意味着当您左键单击按钮时将调用一个回调函数 - copytext()。

函数本身需要稍作修改,因为回调发送事件参数:

def copytext(event):
    copiedtext.set(textentered.get())

编辑: 此行不需要:

copytextButton.configure(command=copytext())

【讨论】:

  • 非常感谢,现在正在运行!有什么理由为什么在这里使用 bind 函数而不是 configure 函数更好?
  • 你没有将函数分配给configure中的命令,而是分配了函数copytext的结果。你应该使用copytextButton.configure(command=copytext)
  • @acw1668 是正确的,最好的解决方案是删除括号(我也错过了这个)。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多