更改标签文本tkin

2024-06-13 16:01:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我从usingpython.com获得了这段代码,它是一个“键入颜色而不是单词”game

我正在使用这段代码来构建这个游戏的一个改进版本,但有问题,我不知道为什么。

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

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时,游戏什么也不做就停止了。

我在想如果我能用一段时间来做这个。。。


Tags: theto代码textconfig游戏ifis
2条回答

更新小部件值

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

您可以使用标签小部件的textvariable选项和StringVar对象、对象的.configure()方法“动态”更改标签小部件的文本值。如上所述,.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(),并覆盖所需的更改

规划图形用户界面

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

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

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

最后,还要查看Model-View-Controller体系结构(及其variants)以获得良好的应用程序设计

初始标签-

    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)

相关问题 更多 >