python - 我正在使用tkinter libary制作一个hangman程序,但出现错误

标签 python python-3.x tkinter error-handling

我正在用python制作“hangman”程序,它遵循与“Hangman”相同的原理,每次遇到错误时,它都会向摇杆人员添加一些东西,我的程序可以正常工作,直到结束为止,因为我尚未完成但基本知识都在那里。图像被显示,并且用户有8次错误尝试(这是错误的地方),图像被显示,当我使用打印语句进行测试以检查变量是否有效时,它们将起作用并且图像被显示,但是在此之后,这错误消息出现,我似乎无法理解原因。我正在使用python 3.8和tkinter库的最新版本。有谁可以帮助我吗?
错误消息是:

Exception in Tkinter callback
Traceback (most recent call last):
  File "E:\Python\lib\tkinter\__init__.py", line 1883, in __call__
    return self.func(*args)
  File "C:/Users/James/Desktop/CollegeComputer Science/HangManGUI.py", line 248, in whenPressed
    canvas.config(canvas.create_image(250,250,image=img))
  File "E:\Python\lib\tkinter\__init__.py", line 1637, in configure
    return self._configure('configure', cnf, kw)
  File "E:\Python\lib\tkinter\__init__.py", line 1622, in _configure
    cnf = _cnfmerge(cnf)
  File "E:\Python\lib\tkinter\__init__.py", line 109, in _cnfmerge
    for c in _flatten(cnfs):
TypeError: object of type 'int' has no len()

代码是:
import time
from tkinter import *
from PIL import ImageTk, Image
import random

foodWords = ["CHOCOLATE", "PIZZA", "SAUSAGE", "BEEF", "CHICKEN"]
sportsWords = ["RUGBY", "FOOTBALL", "CRICKET", "BASEBALL", "BASKETBALL"]
placesWords = ["OLDHAM", "MANCHESTER", "LONDON", "BIRMINGHAM", "LEEDS", "BLACKPOOL", "NEWCASTLE"]

usersGuessList = []
usersGuesses = []

def foodgameSettings():
    global secretWordList
    global secretWord
    global genre
    global secretWord
    global baseattempts

    genre = foodWords
    secretWord = random.choice(genre)
    secretWordList = list(secretWord)
    baseattempts = 8
    foodGame()


def sportsgameSettings():
    global secretWordList
    global secretWord
    global genre
    global secretWord
    global baseattempts

    genre = sportsWords
    secretWord = random.choice(genre)
    secretWordList = list(secretWord)
    baseattempts = 8
    sportsGame()

def placesgameSettings():
    global secretWordList
    global secretWord
    global genre
    global secretWord
    global baseattempts

    genre = placesWords
    secretWord = random.choice(genre)
    secretWordList = list(secretWord)
    baseattempts = 8
    placesGame()

def placesGame():
    global genre
    global secretWordList
    global secretWord
    global genre
    global secretWord
    global usersGuessList
    global usersGuesses
    global usersGuessList
    global usersGuesses
    global entry
    global guess
    global placesgamewind
    global label
    global canvas
    global baseattempts
    global status
    global widget

    def printGuessedLetter():
        print("The word is " + ''.join(usersGuessList))

    for n in secretWordList:
        usersGuessList.append('_')
    printGuessedLetter()

    placesgamewind = Tk()
    genrepicker.destroy()
    widget = placesgamewind
    placesgamewind.title("Hangman")
    canvas = Canvas(height="500",width="500")
    canvas.pack()
    Label(placesgamewind,text="Your word:").pack()
    Label(placesgamewind, text="Has this many letters = "+str(len(secretWordList))).pack()
    label = Label(placesgamewind,text=usersGuessList)
    label.pack()
    status = Label(placesgamewind, text="Guess a letter")
    status.pack()
    guess = StringVar(placesgamewind)
    entry = Entry(placesgamewind,   textvariable=guess)
    submitbtn = Button(placesgamewind, command=whenPressed, text="Submit")
    entry.pack()
    submitbtn.pack()

    placesgamewind.mainloop()

def sportsGame():
    global genre
    global secretWordList
    global secretWord
    global genre
    global secretWord
    global usersGuessList
    global usersGuesses
    global usersGuessList
    global usersGuesses
    global entry
    global guess
    global sportsgamewind
    global label
    global canvas
    global baseattempts
    global status
    global widget

    def printGuessedLetter():
        print("The word is " + ''.join(usersGuessList))

    for n in secretWordList:
        usersGuessList.append('_')
    printGuessedLetter()

    sportsgamewind = Tk()
    genrepicker.destroy()
    widget = sportsgamewind
    sportsgamewind.title("Hangman")
    canvas = Canvas(height="500",width="500")
    canvas.pack()
    Label(sportsgamewind,text="Your word:").pack()
    Label(sportsgamewind, text="Has this many letters = "+str(len(secretWordList))).pack()
    label = Label(sportsgamewind,text=usersGuessList)
    label.pack()
    status = Label(sportsgamewind, text="Guess a letter")
    status.pack()
    guess = StringVar(sportsgamewind)
    entry = Entry(sportsgamewind,   textvariable=guess)
    submitbtn = Button(sportsgamewind, command=whenPressed, text="Submit")
    entry.pack()
    submitbtn.pack()

    sportsgamewind.mainloop()

def foodGame():
    global genre
    global secretWordList
    global secretWord
    global genre
    global secretWord
    global usersGuessList
    global usersGuesses
    global usersGuessList
    global usersGuesses
    global entry
    global guess
    global foodgamewind
    global label
    global canvas
    global baseattempts
    global status
    global widget

    def printGuessedLetter():
        print("The word is " + ''.join(usersGuessList))

    for n in secretWordList:
        usersGuessList.append('_')
    printGuessedLetter()

    foodgamewind = Tk()
    genrepicker.destroy()
    widget = foodgamewind
    foodgamewind.title("Hangman")
    canvas = Canvas(height="500",width="500")
    canvas.pack()
    Label(foodgamewind,text="Your word:").pack()
    Label(foodgamewind, text="Has this many letters = "+str(len(secretWordList))).pack()
    label = Label(foodgamewind,text=usersGuessList)
    label.pack()
    status = Label(foodgamewind,text="Guess a letter")
    status.pack()
    guess = StringVar(foodgamewind)
    entry = Entry(foodgamewind, textvariable=guess)
    submitbtn = Button(foodgamewind, command=whenPressed, text="Submit")
    entry.pack()
    submitbtn.pack()

    foodgamewind.mainloop()

def genrePicker():
    global genrepicker

    genrepicker = Tk()
    main.destroy()
    genrepicker.geometry("250x100")
    genrepicker.title("Genre Picker")
    Label(genrepicker,text="Pick your genre...").pack()
    Button(genrepicker,text="Food",command=foodgameSettings).pack()
    Button(genrepicker,text="Sports",comman=sportsgameSettings).pack()
    Button(genrepicker,text="Places",command=placesgameSettings).pack()

    genrepicker.mainloop()

def whenPressed():
    global baseattempts
    global canvas

    userGuess = guess.get().capitalize()
    print(userGuess)

    entry.delete(0,END)
    usersGuesses.append(userGuess)
    if guess in usersGuesses:
        print("You already guess this letter")
    if baseattempts > 0:
        if userGuess in secretWordList:
            print("Nice Guess!")

            for i in range(len(secretWordList)):
                if userGuess == secretWordList[i]:
                    letterIndex = i
                    usersGuessList[letterIndex] = userGuess.upper()

            print("The word is " + ''.join(usersGuessList))

            label.config(text=usersGuessList)

        if usersGuessList == secretWordList:
            print("You won!")
            widget.destroy()

            win= Tk()
            Label(text="You WON!").pack()
            time.sleep(3)
            win.destroy()
            win.mainloop()#
            mainMenu()

        elif userGuess not in secretWordList:
            baseattempts = baseattempts - 1

            print("Try Again!")

            if baseattempts == 7 :
                path = "No Rope Just stand.png"
                img = ImageTk.PhotoImage(Image.open(path))
                canvas.config(canvas.create_image(250,250,image=img))

            if baseattempts == 6:
                path = "No head just rope.png"
                img = ImageTk.PhotoImage(Image.open(path))
                canvas.config(canvas.create_image(250, 250, image=img))

            if baseattempts == 5:
                path = "Just Head.png"
                img = ImageTk.PhotoImage(Image.open(path))
                canvas.config(canvas.create_image(250, 250, image=img))

            if baseattempts == 4:
                path = "No Leg Stick Man.png"
                img = ImageTk.PhotoImage(Image.open(path))
                canvas.config(canvas.create_image(250, 250, image=img))

            if baseattempts == 3:
                path = "1 Leg Stick Man.png"
                img = ImageTk.PhotoImage(Image.open(path))
                canvas.config(canvas.create_image(250, 250, image=img))

            if baseattempts == 2:
                path = "2 Legs Stick Man.png"
                img = ImageTk.PhotoImage(Image.open(path))
                canvas.config(canvas.create_image(250, 250, image=img))

            if baseattempts == 1:
                path = "One Arm 2 Legs Stick Man.png"
                img = ImageTk.PhotoImage(Image.open(path))
                canvas.config(canvas.create_image(250, 250, image=img))

            if baseattempts == 0:
                path = "Full Stick Man.png"
                img = ImageTk.PhotoImage(Image.open(path))
                canvas.config(canvas.create_image(250, 250, image=img))
                widget.destroy()


    elif baseattempts == 0 and usersGuessList == secretWord:
        if usersGuessList == secretWord:
            print("You won!")
            widget.destroy()
            win = Tk()
            Label(text="You WON!").pack()
            time.sleep(3)
            win.destroy()
            win.mainloop() 


    if baseattempts == 0 and usersGuessList != secretWord:
        print("You lost, hangman died!")
        widget.destroy()
        win = Tk()
        Label(text="You LOST!").pack()
        time.sleep(3)
        win.destroy()
        win.mainloop()  


    if usersGuessList == secretWord:
        print("You won!")
        win = Tk()
        Label(text="You WON!").pack()
        time.sleep(3)
        win.mainloop()
        win.destroy()
        widget.destroy()


def quit():
    main.destroy()

def mainMenu():
    global main

    main = Tk()
    main.geometry("400x150")
    main.title("Main Menu")

    Label(main,text="Welcome to Hangman would you like to play?").pack()
    Button(main,text="Play",command=genrePicker).pack()
    Button(main,text="Quit", command=quit).pack()

    main.mainloop()
    return main

mainMenu()

最佳答案

我相信您想要做的是更新 Canvas ,所以应该代替canvas.config(canvas.create_image(250,250,image=img))

canvas.create_image(250,250,image=img)
canvas.update()
这里有一个棘手的问题,即img变量不是全局变量,因此图像将闪烁然后被放弃。您可以通过在global img之前使用baseattempts = baseattempts - 1来解决此问题

关于python - 我正在使用tkinter libary制作一个hangman程序,但出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64702128/

相关文章:

python - Matplotlib:从二进制数据填充

python - 使用 rauth 来自 fatsecret API 的签名无效

python - 如何键入提示实例级函数(即不是方法)?

python - 使用标签计数构建数据框

python - 使用 pandas.read_csv 索引 DataFrame pandas

python - 从字符串中删除冗余符号

python - pygame.midi.Input.read 不能是字符串

python - 在 tkinter 中使用两个具有相同值的单独检查按钮

Python 视频卡顿

python - 在我的 python Tk 基础应用程序中设置应用程序图标(在 Ubuntu 上)