我正在try 在tkinter创建一个小的刽子手游戏,不幸的是,我的"机会"变量是发挥不好,有点阻止我继续.我想知道是否有人可以看看代码,看看发生了什么,以及如何修复它!(得到一个错误,说它是未定义的,但我已经try 了几次try 来修复它没有成功)

from tkinter import *
from tkinter import messagebox
import random

#Defines the main application size, title, and resizeability with name 'window'
window = Tk()
window.geometry('450x250')
window.resizable(False, False)
window.title("Hangman")
window.canvas = Canvas(window, width=450, height=250)
window.canvas.pack()

def gameEasy(*args):
    hangman = Tk()
    hangman.geometry('450x200')
    hangman.resizable(False, False)
    hangman.title("Hangman")
    hangman.canvas = Canvas(hangman, width=450, height=200)
    hangman.canvas.pack()

    hangman.canvas.create_line(50, 120, 70, 120)
    hangman.canvas.create_line(59, 120, 59, 80)
    hangman.canvas.create_line(59, 80, 39, 80)
    hangman.canvas.create_line(39, 80, 39, 85)

    wordlistEasy = '''cat dog apple stars movie hammer sprint farmer'''
    wordlistEasy = wordlistEasy.split(' ')
    word = random.choice(wordlistEasy)

    letterguessed = []
    chances = len(word) + 2
    correct = 0
    flag = 0
    X1 = 75
    Y1 = 120
    X2 = 85
    Y2 = 120

    for i in word:
        X1 += 12
        X2 += 12
        hangman.canvas.create_line(X1, Y1, X2, Y2, dash=(8,1))
    
    def main_loop(*args):
        Guess = str(GuessInput.get())
        global chances
        incorrectLabel.config(text="")

        while chances != 0 and flag == 0:
            chances -= 1

            if not Guess.isalpha() and Guess != "":
                incorrectLabel.config(text="Please input a LETTER!")
                chances += 1
                break
            elif len(Guess) > 1 and (Guess != word):
                incorrectLabel.config(text="Please input only one letter!")
                chances += 1
                break
            elif (Guess in letterguessed) and Guess != "":
                incorrectLabel.config(text="Letter already guessed!")
                chances += 1
                break
            else:
                letterguessed.append(Guess)
                letterList.config(text=(letterguessed))
                chancesLabel.config(text=f"Chances left: {chances}")
                chances -= 1
                break

        GuessInput.delete(0,"end") #Resets the entry box after each input

    GuessInput = StringVar()
    GuessInput = Entry(hangman, width=8, bd="1")
    GuessInput.place(x=15, y=31)
    GuessInput.focus_force()
    Guessbtn = Button(hangman, text="Guess", width=7, bd="1", command=main_loop).place(x=75, y=28)
    hangman.bind('<Return>', main_loop)

    lettersLabel = Label(hangman, text="Guessed letters:").place(x=220, y=5)
    letterList = Label(hangman, text="")
    letterList.place(x=220, y=20)
    chancesLabel = Label(hangman, text=f"Chances left: {chances}")
    chancesLabel.place(x=12, y=5)
    incorrectLabel = Label(hangman, text="", fg="red")
    incorrectLabel.place(x=12, y=52)

    hangman.mainloop()

def exit(*args):
    messagebox.showinfo("Thank You", "Thanks for playing!")
    window.destroy()

mainlabel = Label(window, text="Welcome to Hangman", font=("Arial Bold",14)).place(x=120, y=5)
introMessage = Message(window, text="This is a simple hangman program using Tkinter. To play, simply select a difficulty, to leave, select quit!", width=280)
introMessage.place(x=80, y=30)

difficultyLabel = Label(window, text="Select a difficulty", font=("Arial Bold",9)).place(x=170, y=70)
easybtn = Button(window, text = "Easy", width=10, bd="1", command=gameEasy).place(x=182, y=95) #Defining a button with properties
hardbtn = Button(window, text = "Hard", width=10, bd="1").place(x=182, y=120) #Defining a button with properties
window.canvas.create_line(175,150,265,150)
rulesbtn = Button(window, text = "Rules", width=10, bd="1").place(x=182, y=155) #Defining a button with properties
quitbtn = Button(window, text = "Quit", width=10, bd="1", command=exit).place(x=182, y=180) #Defining a button with properties

window.mainloop()

试着让机会全局化,试着用几种不同的方法交换函数调用的顺序等等.

推荐答案

chances是函数gameEasy()中的局部变量,所以你不应该在嵌套函数main_loop()中声明它为全局变量. 你应该把它声明为103变量.

同时避免创建多个Tk()个实例. 使用Toplevel()为子窗口.

def gameEasy(*args):
    hangman = Toplevel()  # use Toplevel() instead of Tk() for child window
    ...
    def main_loop(*args):
        ...
        nonlocal chances    # declare chances as nonlocal variable
        ...
    ...

Python相关问答推荐

当密钥是复合且唯一时,Pandas合并抱怨标签不唯一

Pythind 11无法弄清楚如何访问tuple元素

如何将ctyles.POINTER(ctyles.c_float)转换为int?

如何在Windows上用Python提取名称中带有逗号的文件?

Pandas 都是(),但有一个门槛

Pandas计数符合某些条件的特定列的数量

有没有一种ONE—LINER的方法给一个框架的每一行一个由整数和字符串组成的唯一id?

Python列表不会在条件while循环中正确随机化'

以逻辑方式获取自己的pyproject.toml依赖项

在代码执行后关闭ChromeDriver窗口

基于Scipy插值法的三次样条系数

为什么Python内存中的列表大小与文档不匹配?

处理Gekko的非最优解

有没有办法让Re.Sub报告它所做的每一次替换?

来自Airflow Connection的额外参数

如何将一个文件的多列导入到Python中的同一数组中?

在不中断格式的情况下在文件的特定部分插入XML标签

对当前的鼹鼠进行编码,并且我的按键获得了注册

将Pandas DataFrame中的列名的长文本打断/换行为_STRING输出?

将索引表转换为Numy数组