gpt4 book ai didi

python - 战列舰但无法定义

转载 作者:太空宇宙 更新时间:2023-11-04 09:24:20 24 4
gpt4 key购买 nike

我一直在为战舰游戏制作 GUI,但是当代码运行时出现错误:

A1.configure(relief=SUNKEN)

NameError: 名称 'A1' 未定义

我意识到按钮是在 def 函数中命名的,所以我将它们设为 global 但是仍然出现相同的错误。然而,我对 global 还很陌生,我不确定我是否正确使用了它。

from tkinter import*
import random
import time

##### main
window = Tk()
window.title("battleships")

# makes every button global
global A1
global A2
global A3
global B1
global B2
global B3
global C1
global C2
global C3

# command that places the buttons when the ships are placed
def placeships():
A1 = Button(window, width=5, height=2, text="A1", command=clickA1).place(x=0, y=0)
A2 = Button(window, width=5, height=2, text="A2", command=clickA2).place(x=50, y=0)
A3 = Button(window, width=5, height=2, text="A3", command=clickA3).place(x=100, y=0)
B1 = Button(window, width=5, height=2, text="B1", command=clickB1).place(x=0, y=50)
B2 = Button(window, width=5, height=2, text="B2", command=clickB2).place(x=50, y=50)
B3 = Button(window, width=5, height=2, text="B3", command=clickB3).place(x=100, y=50)
C1 = Button(window, width=5, height=2, text="C1", command=clickC1).place(x=0, y=100)
C2 = Button(window, width=5, height=2, text="C2", command=clickC2).place(x=50, y=100)
C3 = Button(window, width=5, height=2, text="C3", command=clickC3).place(x=100, y=100)

# commands for the buttons
def clickA1():
A1.configure(relief=SUNKEN)
def clickA2():
A2.configure(relief=SUNKEN)
def clickA3():
A3.configure(relief=SUNKEN)
def clickB1():
B1.configure(relief=SUNKEN)
def clickB2():
B2.configure(relief=SUNKEN)
def clickB3():
B3.configure(relief=SUNKEN)
def clickC1():
C1.configure(relief=SUNKEN)
def clickC2():
C2.configure(relief=SUNKEN)
def clickC3():
C3.configure(relief=SUNKEN)

placeships()

我是否正确使用了 global?如果是,为什么会出现错误?

最佳答案

您没有正确使用 global。您必须在函数内将它们声明为全局:

def placeships():
global A1, A2, ...

关于python - 战列舰但无法定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58529433/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com