我一直在玩tkinter一点,我发现你必须做一个def方法来使用按钮。所以我想做13个按钮,因为我想做一个计算器,但我真的不想做13个def方法,做非常相似的事情。我尝试了一个嵌套的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)
您可以创建一个返回函数的函数。你知道吗
例如
这在功能上应该与上面的[number]b函数相同。你知道吗
相关问题 更多 >
编程相关推荐