简体   繁体   English

通过按一下按钮在tkinter中更新标签

[英]Update a label in tkinter from a button press

My question is regarding GUI programming in python by using tkinter. 我的问题是关于使用tkinter在python中进行GUI编程的问题。 I believe this is Python 3x. 我相信这是Python 3x。

My question: While we're executing a program to run the GUI, can a button update a label? 我的问题:在执行程序以运行GUI时,按钮可以更新标签吗? More specifically, is there a way to change the labels displayed text after pushing the button? 更具体地说,有没有办法在按下按钮后更改标签显示的文本? I have consulted stack overflow on this before and adopted the StringVar() method, but it doesn't seem to fix my problem, in fact it omits the text from the GUI completely! 我之前已对此进行过堆栈溢出咨询,并采用了StringVar()方法,但它似乎无法解决我的问题,实际上它完全忽略了GUI中的文本!

Here is the code below 这是下面的代码

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

Any help would be appreciated! 任何帮助,将不胜感激!

What you have to do is to bind a Button event to the copytextButton object like so: 您要做的就是将Button事件绑定到copytextButton对象,如下所示:

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

This means that a callback function - copytext() will be called when you left-click the button. 这意味着,当您左键单击按钮时,将调用一个回调函数-copytext()。

A slight modification is needed in the function itself, since the callback sends an event argument: 由于回调函数发送一个事件参数,因此需要对函数本身进行一些修改:

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

Edit: This line is not needed: 编辑:不需要此行:

copytextButton.configure(command=copytext())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM