更改标签文本tkinter

时间:2017-02-18 21:38:14

标签: python tkinter

我从usingpython.com获得了这个代码,这是"键入的颜色不是单词" game

我正在使用此代码构建此游戏的改进版本,并且出现了问题,我无法理解为什么。

所以,我想改变单词所在的标签(名为"标签"),改为" Game Over!你的分数是bla bla bla"当倒计时达到0.所以,我这样做了(我添加的只是最后两行):

def nextColour():

#use the globally declared 'score' and 'play' variables above.
global score
global timeleft

#if a game is currently in play...
if timeleft > 0:

    #...make the text entry box active.
    e.focus_set()

    #if the colour typed is equal to the colour of the text...
    if e.get().lower() == colours[1].lower():
        #...add one to the score.
        score += 1

    #clear the text entry box.
    e.delete(0, tkinter.END)
    #shuffle the list of colours.
    random.shuffle(colours)
    #change the colour to type, by changing the text _and_ the colour to a random colour value
    label.config(fg=str(colours[1]), text=str(colours[0]))
    #update the score.
    scoreLabel.config(text="Score: " + str(score))

elif timeleft == 0:
    ĺabel.config(text="Game Over! Your score is: " + score)

这不起作用。当倒计时达到0时,游戏什么都不做并停止。

我在考虑是否可以使用while循环执行此操作...

2 个答案:

答案 0 :(得分:4)

更新小部件值

有关详细信息,请参阅this answer

您可以使用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")

使用.configure()

# ...

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

#NB: .config() can also be used
my_label.configure(text="New String")

有关详细信息,请参阅effbot.org

调试检查

如果不查看所有代码,我还建议您查看下面列出的各种其他问题,以了解可能的原因。 为了扩展您的意见(在这篇文章中),可能有多种原因导致该计划无法按预期“运作”:

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

规划您的GUI

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

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

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

最后,还要了解Model-View-Controller架构(及其variants)以获得良好的应用程序设计

答案 1 :(得分:-1)

初始标签-

    lbl_selection_value1=Label(root, text="Search Option 1")
    lbl_selection_value1.grid(row=0,column=0,padx=1)

更新的标签-

    lbl_selection_value1.destroy()
    lbl_selection_value1_updated = Label(root, text='New Text')
    lbl_selection_value1_updated.grid(row=0, column=0, padx=1)
相关问题