首页 > 解决方案 > 如何在 tkinter 中刷新屏幕以显示新的标签文本?

问题描述

下面是我的代码,我正在为自己制作一个有趣的刽子手游戏,以适应 Tkinter 库/GUI 创建和 python 语言。在用户输入猜测以使用标签向用户提供反馈后,我在刷新 GUI 时遇到了一些障碍。我读到使用标签,所以你可以附加一个字符串变量,这样你就可以更改文本,但我无法弄清楚。无论出于何种原因,我的 Tkinter 标签“text_out”都没有显示。提前感谢您的帮助!此外,我是新手和初学者程序员,所以任何关于如何更好地组织自己的意见也会很棒。

    from tkinter import *
    import random

    root = Tk()
    root.wm_title("Hangman")

    w = Canvas(root, width=1000,height=650)
    #drawing the hangmaan image setup
    w.create_rectangle(250,0,450,25, fill = "brown") #top beam
    w.create_rectangle(250,0,275,100, fill = "brown") #hanging part
    w.create_rectangle(475,0,450,400, fill = "brown") #middle upright
    w.create_rectangle(300,400,600,425, fill = "brown") #platform
    w.pack()

    alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y",
        "z"] #keeps track of letters used
    words = ["atmosphere", "miscellaneous","muffins","junk","pajamas","engineering","privilege","amplifier","countryside","python",
     "magic","hats","flash","clock","ceiling"] #random word choices for the answer

    word_choice = random.choice(words) #chooses word from list of words for         the answer
    print(word_choice) #for debugging
    mult = len(word_choice) #length of word to create underscore string 
    underscores = "_ "*mult #underscore string 
    print(underscores) #for debugging
    w.create_text(500,600, font= ("Purisa", 48), text = underscores) #underscores in gui output

    guess_out = "$" #text varavable to be changed as a result of user guess
    text_out = Label(root,font=("Purisa", 18),textvariable="Test").place(x=650,y=200) #results of user guess text on screen

    guess_bar_label = Label(root, font = ("Purisa", 20), text = "Guess: ").place(x=600, y=285) #label for the text bar
    guess_var = StringVar() #varaiable for the text bar
    guess_bar = Entry(root, textvariable=guess_var).place(x=700, y=300) #text bar for user input


    def Guess():
        #logic test 
        print(guess_var.get())
        if len(str(guess_var.get()))==1: #makes sure input is only one charactar
            print("one char")
            if str(guess_var.get()) in alphabet: #makes sure is still a choice and not one they have picked already
                print("in alphabet") #for debugging
                guess_out = "that is in the alphabet" #GUI output text change for user to see
                root.update_idletasks() #failed attemped to refresh screen
                alphabet.remove(str(guess_var.get())) #removes choice after use and guess goes through

        elif len(str(guess_var.get()))>1: #result if input is too long
            print("too many chaactar")


    w = Button (root,command=Guess, text="Check").place(x=850, y=300) #submit button for users guess from entry bar


    root.mainloop()

标签: python-3.xuser-interfacetkinter

解决方案


您可以创建一个按钮来删除当前显示所在的框架。删除后,在父级中绘制一个新框架并使用刷新的框架添加所有新代码


推荐阅读