我正在尝试猜测数字游戏,它会选择一个随机数,然后如果你选择了正确的按钮,它说你是正确的,如果你选错了它就说不正确。
print("~Guess the Number~")
print("Pick any number")
topFrame=Frame(root)
bottomFrame=Frame(root)
topFrame.pack(side=TOP)
bottomFrame.pack(side=BOTTOM)
#Random Number
import random
b=(random.randint(1,4))
#Functions
def number1(event,b):
if b==1:
print("You guessed the correct number")
else:
print("Not the correct number")
def number2(event,b):
if b==2:
print("You guessed the correct number")
else:
print("Not the correct number")
def number3(event,b):
if b==3:
print("You guessed the correct number")
else:
print("Not the correct number")
def number4(event,b):
if b==4:
print("You guessed the correct number")
else:
print("Not the correct number")
#Where the buttons are
button1=Button(topFrame,text="1")
button2=Button(topFrame,text="2")
button3=Button(topFrame,text="3")
button4=Button(topFrame,text="4")
button5=Button(bottomFrame,text="Quit")
#Binding the buttons
button1.bind("<Button-1>",number1)
button1.pack(side=LEFT)
button2.bind("<Button-2>",number2)
button2.pack(side=LEFT)
button3.bind("<Button-3>",number3)
button3.pack(side=LEFT)
button4.bind("<Button-4>",number4)
button4.pack(side=LEFT)
button5.pack()
它给了我:
__init__.py", line 1550, in __call__
return self.func(*args)
TypeError: number1() missing 1 required positional argument: 'b'
我对python还不太了解:/
答案 0 :(得分:0)
你的函数需要两个参数
def number1(event, b):
但bind()
始终只发送一个 - event
。
您可以使用lambda
发送更多参数
bind(`<Button-1>`, lambda event: number1(event, b))
BTW <Button-1>
,<Button-2>
等等意味着鼠标按钮
<Button-1>
是鼠标左键
<Button-2>
是鼠标中键
<Button-3>
是鼠标右键。
BUtton()
有参数command=
来分配函数,它不会发送event
button1 = Button(topFrame, text="1", command=lambda:number1(b))
def number1(b):
# ...
但你可以为所有按钮创建一个功能
def check_number(b, button_number):
if b == button_number:
print("You guessed the correct number")
else:
print("Not the correct number")
button1 = Button(topFrame, text="1", command=lambda:check_number(b, "1"))
button2 = Button(topFrame, text="2", command=lambda:check_number(b, "2"))
button3 = Button(topFrame, text="3", command=lambda:check_number(b, "3"))
button4 = Button(topFrame, text="4", command=lambda:check_number(b, "4"))