使用Python更新标签Tkinter

时间:2018-05-30 12:47:37

标签: python tkinter label

我正在制作一个Hangman类型的游戏。到目前为止,我已经编写了运行良好的CLI版本,我只是将其移植到创建GUI。

我已经陷入困境:-(。该计划尚未完成,还有更多工作要做,但我有两个问题。第一个是标签更新。

当选择一个字母时,它会为字母创建足够的破折号,并将其放在一个名为“字母”的标签中。

当用户输入一个字母时,它会替换破折号,但是它会在旧标签旁边添加一个新标签,而我想替换此标签。我尝试过使用.set()但这似乎不起作用。

我的第二个问题,这更像是一个逻辑错误(我认为),是我想跟踪输入的字母,以便我可以将其与新输入的字母进行比较并提醒用户。这很有效,但是当输入一个字母时,即使它是第一次输入,它也会警告用户。

以下是代码:

import tkinter
from tkinter import *
from tkinter import messagebox
import random

guesses = 8

def play():
    print("play game")

    wordList = ["talking", "dollar","choice", "famous", "define", "features"]

    wordChoice = random.choice(wordList)

    print(wordChoice)
    wordLength = (len(wordChoice))
    print(wordLength)
    guessedLetters = []
    dashes = []

    def enterLetter():
        print("Guess")
        global guesses

        print(guessedLetters)

        while guesses != 0:
            guess = entry.get().lower()

            if len(guess) >1:
                messagebox.showinfo("Error","Sorry, only one letter at a time")
                entry.delete("0","end")
                return
            elif guess.isalpha() == False:
                messagebox.showinfo("Error","Letters only please")
                entry.delete("0","end")
                return
            elif guess in guessedLetters:
                messagebox.showinfo("Error","You have already used the letter")
                entry.delete("0","end")
                return

            guessedLetters.append(guess)
            print(guessedLetters)
            print(guesses)
            count = 0


            for i in range(wordLength):
                if wordChoice[i] == guess:
                    dashes[i] = guess
                    count = count +1
                    letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10)

            if count == 0:
                guesses -= 1

            if guesses == 0:
                print("You have ran out of guesses!")
                print("The word was:",wordChoice)

    ######  Play Game GUI


    play = Toplevel()
    play.title("Play Hangman!")

    label = Label(play, text="HANGMAN", font = ("Arial",16)).grid(row = 0)
    label = Label(play, text="Enter your guess >").grid(row = 3, column = 0)

    for i in range(wordLength):
        dashes.append("-")

    letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10)


    entry = Entry(play)
    entry.grid(row = 3, column = 1, columnspan = wordLength) 
    enterButton = Button(play, text = "Enter Guess", width = 15, command = enterLetter).grid(row = 3, column = (wordLength+2))
    label = Label(play, text = "Letter used: ").grid(row = 4, columnspan = 2)
    label = Label(play, text = "").grid(row= 4, columnspan = 6)



def scores():
    print("check scores")

def howToPlay():
    print("how to play")



####### Main Menu

root = Tk()
root.geometry("500x300")                                                                    
root.title("HANGMAN")
label = Label(root, text="HANGMAN", font = ("Arial",30)).grid(row = 0, columnspan = 3)
label = Label(root, text = "Option 1 :", font = ("Arial",12)).grid(row = 1, column = 1)    
playButton = Button(root, text = "Play Game", width = 15, command = play).grid(row = 1, column = 2) 
label = Label(root, text = "Option 2 :", font = ("Arial",12)).grid(row = 2, column = 1)
instructionsButton = Button(root, text = "How to play", width = 15, command = howToPlay).grid(row = 2, column = 2) 
label = Label(root, text = "Option 3 :", font = ("Arial",12)).grid(row = 3, column = 1) 
scoresButton = Button(root, text = "View Scores", width = 15, command = scores).grid(row = 3, column = 2) 
label = Label(root, text = "Option 4 :", font = ("Arial",12)).grid(row = 4, column = 1)
exitButton = Button(root, text = "Exit", width = 15, command = exit).grid(row = 4, column = 2)


root.mainloop()

2 个答案:

答案 0 :(得分:1)

您无法更新标签的原因是因为您尚未将其存储在任何变量中。 Label对象和所有其他小部件的grid,pack和place函数返回None,因此当您调用时:

letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10)

您的标签无法通过可变字母访问。要解决此问题,您应该将其拆分为:

letter = Label(play, text = dashes, font = ("Arial",20))
letter.grid(row = 2, column = i+1,padx = 10, pady =10)

要更新该标签的文字,您可以在其上调用.configure(text = 'new text')

# letter = Label(play, text = dashes, font = ("Arial",20)).grid(row = 2, column = i+1,padx = 10, pady =10)    # 

letter.configure(text = dashes)

至于你的第二个问题,我认为你在函数while中混淆了if循环和enterLetter语句。每次点击都会调用一次,如果玩家的猜测已经用完,你只需要检查一次。

if guesses != 0:
    ...

elif guesses == 0:
    ....

答案 1 :(得分:1)

  1. 您需要配置标签,而不是重新创建它。
  2. 为什么在enter_letter中使用while循环?它只是在单击Button时运行,它需要是if guesses > 0:
  3. 输入正确的单词时,您的程序没有终止;我添加了这个。
  4. 代码:

    import tkinter
    from tkinter import *
    from tkinter import messagebox
    import random
    
    guesses = 8
    
    letter = None
    
    def play():
        global letter
    
        print("play game")
    
        wordList = ["talking", "dollar","choice", "famous", "define", "features"]
    
        wordChoice = random.choice(wordList)
    
        print(wordChoice)
        wordLength = (len(wordChoice))
        print(wordLength)
        guessedLetters = []
        dashes = []
    
    
        play = Toplevel()
        play.title("Play Hangman!")
    
        label = Label(play, text="HANGMAN", font = ("Arial",16)).grid(row = 0)
        label = Label(play, text="Enter your guess >").grid(row = 3, column = 0)
    
        for i in range(wordLength):
            dashes.append("-")
    
        letter = Label(play, text = dashes, font = ("Arial",20))
        letter.grid(row = 2, column = i+1,padx = 10, pady =10)
        print(letter)
    
        def enterLetter():
            print("Guess")
            global guesses, letter
    
            print(guessedLetters)
    
            if guesses != 0:
                guess = entry.get().lower()
    
                if len(guess) >1:
                    messagebox.showinfo("Error","Sorry, only one letter at a time")
                    return
                elif guess.isalpha() == False:
                    messagebox.showinfo("Error","Letters only please")
                    return
                elif guess in guessedLetters:
                    messagebox.showinfo("Error","You have already used the letter")
                    return
                entry.delete("0","end")
                guessedLetters.append(guess)
                #print(guessedLetters)
                #print(guesses)
                print(dashes)
                count = 0
    
    
                for i in range(wordLength):
                    if wordChoice[i] == guess:
                        dashes[i] = guess
                        count += 1
                        letter.configure(text = dashes)
    
    
                if count == 0:
                    guesses -= 1
    
                if "".join(dashes) == wordChoice:
                    print("succsess!")
                    play.destroy()
                    return
    
                if guesses == 0:
                    print("You have ran out of guesses!")
                    print("The word was:",wordChoice)
    
        ######  Play Game GUI
    
    
        entry = Entry(play)
        entry.grid(row = 3, column = 1, columnspan = wordLength) 
        enterButton = Button(play, text = "Enter Guess", width = 15, command = enterLetter).grid(row = 3, column = (wordLength+2))
        label = Label(play, text = "Letter used: ").grid(row = 4, columnspan = 2)
        label = Label(play, text = "").grid(row= 4, columnspan = 6)
    
    
    
    def scores():
        print("check scores")
    
    def howToPlay():
        print("how to play")
    
    
    
    ####### Main Menu
    
    root = Tk()
    root.geometry("500x300")                                                                    
    root.title("HANGMAN")
    label = Label(root, text="HANGMAN", font = ("Arial",30)).grid(row = 0, columnspan = 3)
    label = Label(root, text = "Option 1 :", font = ("Arial",12)).grid(row = 1, column = 1)    
    playButton = Button(root, text = "Play Game", width = 15, command = play).grid(row = 1, column = 2) 
    label = Label(root, text = "Option 2 :", font = ("Arial",12)).grid(row = 2, column = 1)
    instructionsButton = Button(root, text = "How to play", width = 15, command = howToPlay).grid(row = 2, column = 2) 
    label = Label(root, text = "Option 3 :", font = ("Arial",12)).grid(row = 3, column = 1) 
    scoresButton = Button(root, text = "View Scores", width = 15, command = scores).grid(row = 3, column = 2) 
    label = Label(root, text = "Option 4 :", font = ("Arial",12)).grid(row = 4, column = 1)
    exitButton = Button(root, text = "Exit", width = 15, command = exit).grid(row = 4, column = 2)
    
    
    root.mainloop()
    

    我希望这会对你有所帮助。