我被要求编辑我的代码,所以我决定包含整个计算器脚本
from tkinter import * global choice choice = 0 #Program def calculate(*event): if choice == 1: try: add1 = ccalc1.get() add2 = ccalc2.get() except: no = Label(app, text="You must use a number").grid(row=0, column=0) answ = add1 + add2 answer = Label(app, text = answ).grid(row=1, column=0) elif choice == 2: try: sub1 = ccalc1.get() sub2 = ccalc2.get() except: no = Label(app, text="You must use a number").grid(row=1, column=0) answ = sub1 - sub2 answer = Label(app, text = answ).grid(row=1, column=0) def choice2(): global choice choice = 2 #End Program #GUI #Window Info calc = Tk() calc.title("Calculator") calc.geometry("200x140") #End Window Info #Build Window app = Frame(calc) app.grid() ccalc1 = IntVar() ccalc2 = IntVar() #Widgets if choice == 0: welcome = Label(app, text="Select a choice") elif choice == 2: welcome.config(text="Subtraction") calcbox1 = Entry(app,textvariable=ccalc1) calcbox2 = Entry(app,textvariable=ccalc2) submit = Button(app, text="CALCULATE", command = calculate) welcome.grid(row=0,column=0) calcbox1.grid(row=2, column=0) calcbox2.grid(row=3, column=0) submit.grid(row=4, column=0) calc.bind('<Return>', calculate) #End Widgets #Menu menu=Menu(calc) #Operations filemenu = Menu(menu,tearoff=0) filemenu.add_command(label="Subtract", command = choice2) menu.add_cascade(label="Operations",menu=filemenu) calc.config(menu=menu) calc.mainloop() #End GUI
欢迎标签文字不会相应改变是错误的。
更新:我收录了整个计算器代码
感谢任何帮助。
答案 0 :(得分:0)
很难理解你期望发生的事情。例如,看看这段代码:
#Widgets
if choice == 0:
welcome = Label(app, text="Select a choice")
elif choice == 2:
welcome.config(text="Subtraction")
此代码只会执行一次,并且选择将始终为零,因为这是您初始化它的内容。它执行一次因为它不在函数中而不在循环中,所以当python解析代码时它将运行它并移动到下一行。该文本块将永远不会再次处理。
如果您希望在用户选择菜单项时更改标签,则需要在choice2
函数中执行该代码:
def choice2():
global choice
choice = 2
welcome.config(text="Subtraction")