我一直在玩tkinter一点点,我发现你必须使用def方法来使用按钮。所以我想制作13个按钮,因为我想制作一个计算器,但我真的不想制作13种非常类似的方法。我试过做一个嵌套的def方法(我之前从未真正做过),但是,从我尝试过的方法来看,它不会起作用。我只是做错了还是不可能。如果不可能的话,除了大量的复制和大量粘贴之外,还有其他方法可以批量生产def方法吗?这是代码:
from tkinter import *
window=Tk()
window.geometry("500x500")
print("Restarting")
user=""
def oneb():
global user
print("1",end="")
user+="1"
def twob():
global user
user+="2"
print("2",end="")
def threeb():
global user
user+="3"
print("3",end="")
def fourb():
global user
user+="4"
print("4",end="")
def fiveb():
global user
user+="5"
print("5",end="")
def sixb():
global user
user+="6"
print("6",end="")
def sevenb():
global user
user+="7"
print("7",end="")
def eightb():
global user
user+="8"
print("8",end="")
def nineb():
global user
user+="9"
print("9",end="")
def zerob():
global user
user+="0"
print("0",end="")
def plusb():
global user
user+="+"
print("+",end="")
def minusb():
global user
print("-",end = "")
def equalb():
global user
if "+" in user:
user=user.partition("+")
symbol="+"
elif "-" in user:
user=user.partition("-")
symbol="-"
else:
print("=",user)
num1=user[0]
num2=user[2]
num1=int(num1)
num2=int(num2)
if symbol=="+":
answer=num1+num2
else:
answer=num1-num2
answer=str(answer)
print("="+answer)
heightb=5
widthb=10
#I know here I probably should've just made a def method.
one=Button(window, text="1",command=oneb,height=heightb,width=widthb)
one.grid(row=1,column=1)
two=Button(window, text="2",command=twob,height=heightb,width=widthb)
two.grid(row=1,column=2)
three=Button(window, text="3",command=threeb,height=heightb,width=widthb)
three.grid(row=1,column=3)
four=Button(window, text="4",command=fourb,height=heightb,width=widthb)
four.grid(row=2,column=1)
five=Button(window, text="5",command=fiveb,height=heightb,width=widthb)
five.grid(row=2,column=2)
six=Button(window, text="6",command=sixb,height=heightb,width=widthb)
six.grid(row=2,column=3)
seven=Button(window, text="7",command=sevenb,height=heightb,width=widthb)
seven.grid(row=3,column=1)
eight=Button(window, text="8",command=eightb,height=heightb,width=widthb)
eight.grid(row=3,column=2)
nine=Button(window, text="9",command=nineb,height=heightb,width=widthb)
nine.grid(row=3,column=3)
zero=Button(window, text="0",command=zerob,height=heightb,width=widthb)
zero.grid(row=4,column=2)
plus=Button(window, text="+", command=plusb,height=heightb, width=widthb)
plus.grid(row=2,column=4)
minus=Button(window,text="-", command=minusb,height=heightb, width=widthb)
minus.grid(row=1,column=4)
equal=Button(window,text="=", command=equalb,height=heightb, width=widthb)
equal.grid(row=3,column=4)
mainloop()
#button location var.grid(row=x,column=x)
答案 0 :(得分:1)
您可以创建一个返回函数的函数。
例如,
def build_button(number):
def button():
global user
user += str(number)
print(number, end="")
return button
oneb = build_button(1)
twob = build_button(2)
# ...
这应该在功能上与您上面的[number] b功能完全相同。