我在获取执行命令的按钮时遇到问题。(特金特)



我正在制作一款自选冒险游戏,我正试图创建一个系统,其中有一个在True和amp;False表示玩家下一步要去哪里。此外,我将使用条件语句来指定事件的逻辑和流程,为了让逻辑等待GUI,我还添加了一个"count"变量,每次单击按钮时该变量都会增加1,这样只有当计数大于0时,逻辑才会运行。然而,当我制作这两个功能并将它们设置为按钮的命令时,在我真正按下按钮之前,它们一直在执行。这是代码:

def ButA() :
global count
count += 1
Decision = True
def ButB() :
global count
count += 1
Decision = False

# GUI:
if Player == 0 :
root = tkinter.Tk()
canvas = tkinter.Canvas(root, width=960, height=720)
image = ImageTk.PhotoImage(Image.open('TitleScreen.png'))
canvas.create_image(0, 0, anchor=tkinter.NW, image=image)
textbox = canvas.create_text(485, 375, font=("Times", 25, 'bold'),
text='Welcome, press A to proceed, press B to quit [a/b]', fill='white',
justify='center')
opt1 = Button(root, text='A', command=ButA(), bg='black', bd=5, font=('Times', 20), activebackground='blue',
activeforeground='black', fg='black')
opt1.place(x=435, y=465)
opt2 = Button(root, text='B', bg='black', bd=5, font=('Times', 20), activebackground='blue',
activeforeground='black', fg='black', command=ButB())
opt2.place(x=485, y=465)

Decision的值被设置为进一步向上,count的值被设定为0。每当我运行脚本时,我都会看到数字2出现在屏幕中间,这表明出于某种原因,无论何时我运行脚本,它都会执行两个函数一次,而不是在按下按钮时做出反应,然后只会给我结果。我做错了什么?

在创建按钮时将命令绑定到按钮时,请尝试以下操作:

command=labmda: ButA()

否则,一旦创建按钮,就会调用您的函数。

您不需要括号,只需使用command=ButA而不是command=ButA()。否则,它将在按钮的定义处立即调用函数。

opt1 = Button(root, text='A', command=ButA, bg='black', bd=5, font=('Times', 20), activebackground='blue',
activeforeground='black', fg='black')
# [...]
opt2 = Button(root, text='B', bg='black', bd=5, font=('Times', 20), activebackground='blue',
activeforeground='black', fg='black', command=ButB)

最新更新