更改标签文本 tkinter

1 python tkinter

我从 usingpython.com 获得了这段代码,这是一个“输入颜色而不是单词”的游戏

\n\n

我正在使用这段代码构建该游戏的改进版本,但出现了问题,我不明白为什么。

\n\n

所以,我想在倒计时达到 0 时将单词所在的标签(名为“标签”)更改为“游戏结束!你的分数是 bla bla bla”。所以,我这样做了(我添加的只是最后两行):

\n\n
def nextColour():\n\n#use the globally declared \'score\' and \'play\' variables above.\nglobal score\nglobal timeleft\n\n#if a game is currently in play...\nif timeleft > 0:\n\n    #...make the text entry box active.\n    e.focus_set()\n\n    #if the colour typed is equal to the colour of the text...\n    if e.get().lower() == colours[1].lower():\n        #...add one to the score.\n        score += 1\n\n    #clear the text entry box.\n    e.delete(0, tkinter.END)\n    #shuffle the list of colours.\n    random.shuffle(colours)\n    #change the colour to type, by changing the text _and_ the colour to a random colour value\n    label.config(fg=str(colours[1]), text=str(colours[0]))\n    #update the score.\n    scoreLabel.config(text="Score: " + str(score))\n\nelif timeleft == 0:\n    \xc4\xbaabel.config(text="Game Over! Your score is: " + score)\n
Run Code Online (Sandbox Code Playgroud)\n\n

这是行不通的。当倒计时达到 0 时,游戏什么也不做并停止。

\n\n

我在想是否可以用 while 循环来做到这一点......

\n

Jam*_*han 5

更新小部件值

有关更多详细信息,请参阅此答案。

您可以使用对象的textvariable选项对象的方法“动态”更改标签小部件的文本值。正如上面的答案中提到的,该方法的优点是减少了一个需要跟踪的对象StringVar.configure()Label.configure()

textvariableStringVar

# Use tkinter for Python 3.x
import Tkinter as tk
from Tkinter import Label

root = tk.Tk()

# ...
my_string_var = tk.StringVar(value="Default Value")

my_label = Label(root, textvariable=my_string_var)
my_label.pack()

#Now to update the Label text, simply `.set()` the `StringVar`
my_string_var.set("New text value")
Run Code Online (Sandbox Code Playgroud)

.configure()

# ...

my_label = Label(root, text="Default string")
my_label.pack()

#NB: .config() can also be used
my_label.configure(text="New String")
Run Code Online (Sandbox Code Playgroud)

请参阅effbot.org了解更多详细信息。

调试检查

在不查看所有代码的情况下,我还建议检查下面列出的各种其他问题以查找可能的原因。为了扩展您的评论(在这篇文章中),程序无法按预期“工作”的原因可能有多种:

  • 程序永远不会进入最终if块 ( if timeleft == 0),因此该.config方法没有机会更新变量
  • 全局变量timeleft确实达到了0,但在迭代之后,它会递增0并重新进入第一个if块(if timeleft>0),从而覆盖.config()您想要的。
  • 代码的另一部分可能会.config()在您的小部件上调用 a 并覆盖您所需的更改

规划你的图形用户界面

为了防止这些事情发生,我强烈建议退后一步,拿一些笔和纸并考虑应用程序的整体设计。具体问问自己:

  • 用户如何与这个小部件交互?哪些操作/事件会导致此小部件发生更改?
  • 想一想这些事件的所有组合,并问问自己这些事件是否相互冲突。

还可以考虑为应用程序绘制一个流程图,从用户启动应用程序到关闭应用程序之前可以采取的可能路径,确保流程中的块不会相互矛盾。

最后,还要了解模型-视图-控制器架构(及其变体)以实现良好的应用程序设计