使 Tkinter 小部件根据来自另一个小部件的输入进行更改
Causing a Tkinter widget to change based on input from another widget
我已经创建了一个简单的命令行游戏,正在考虑将其移植到 GUI。这样我就可以让玩家通过点击按钮进行选择,而不是被迫输入文本。
我的问题是,如果不能更改 Label 和 Button 小部件上的文本,这样做会很棘手,那么如何才能正确地做到这一点呢?
这是我目前的情况(在 laurencevs 的回答之后):
def goAway(event):
label02.configure(text = " ")
label01.configure(text = "Go away")
time.sleep(1)
label01.configure(text = "GO AWAY.")
time.sleep(1)
label01.configure(text = "Seriously, go AWAY!")
time.sleep(1)
label01.configure(text = "That's it.")
time.sleep(0.5)
quit("GOODBYE.")
button01 = Button(root, text="Click me, see what happens.")
button01.grid(row=1001, column=1001)
button01.bind("<Button-1>", goAway)
但它所做的只是等待 3 秒,然后关闭程序。我该如何解决这个问题
这个想法是,当点击按钮时,标签 label01
中的文本将更改为 "Go away",等待一秒钟,将文本更改为 "GO AWAY.",等等,然后退出,在终端中向用户 运行 打印 "GOODBYE"。
您绝对可以更改标签或按钮上的文本。
您所要做的就是使用Label.configure()
方法。假设您想将 label1
中的文本更改为 "Don't Panic",您只需这样做:
label1.configure(text = "Don't Panic")
按钮和其他小部件也是如此。
如果您想创建一个在单击时执行此操作的按钮,您必须定义一个函数来更改标签的文本,然后在创建按钮时使用该函数的名称(例如 foo
)像这样:
button = Button(window, text = "I am a button", command = foo)
完整的代码如下所示:
from tkinter import * # Tkinter in Python 2
def foo():
label1.configure(text = "Don't Panic")
window = Tk()
# other (optional) window setup here
label1 = Label(window, text = "")
button = Button(window, text = "I am a button", command = foo)
# pack the label and button and initiate the window's mainloop here
我已经创建了一个简单的命令行游戏,正在考虑将其移植到 GUI。这样我就可以让玩家通过点击按钮进行选择,而不是被迫输入文本。
我的问题是,如果不能更改 Label 和 Button 小部件上的文本,这样做会很棘手,那么如何才能正确地做到这一点呢?
这是我目前的情况(在 laurencevs 的回答之后):
def goAway(event):
label02.configure(text = " ")
label01.configure(text = "Go away")
time.sleep(1)
label01.configure(text = "GO AWAY.")
time.sleep(1)
label01.configure(text = "Seriously, go AWAY!")
time.sleep(1)
label01.configure(text = "That's it.")
time.sleep(0.5)
quit("GOODBYE.")
button01 = Button(root, text="Click me, see what happens.")
button01.grid(row=1001, column=1001)
button01.bind("<Button-1>", goAway)
但它所做的只是等待 3 秒,然后关闭程序。我该如何解决这个问题
这个想法是,当点击按钮时,标签 label01
中的文本将更改为 "Go away",等待一秒钟,将文本更改为 "GO AWAY.",等等,然后退出,在终端中向用户 运行 打印 "GOODBYE"。
您绝对可以更改标签或按钮上的文本。
您所要做的就是使用Label.configure()
方法。假设您想将 label1
中的文本更改为 "Don't Panic",您只需这样做:
label1.configure(text = "Don't Panic")
按钮和其他小部件也是如此。
如果您想创建一个在单击时执行此操作的按钮,您必须定义一个函数来更改标签的文本,然后在创建按钮时使用该函数的名称(例如 foo
)像这样:
button = Button(window, text = "I am a button", command = foo)
完整的代码如下所示:
from tkinter import * # Tkinter in Python 2
def foo():
label1.configure(text = "Don't Panic")
window = Tk()
# other (optional) window setup here
label1 = Label(window, text = "")
button = Button(window, text = "I am a button", command = foo)
# pack the label and button and initiate the window's mainloop here