簡體   English   中英

tkinter:如何在程序本身內部更改標簽

[英]tkinter: How to change labels inside the program itself

我被要求編輯我的代碼,所以我決定包括整個計算器腳本

 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 

錯誤的是,歡迎標簽文本不會相應更改。

更新:我包括了整個計算器代碼

任何幫助表示贊賞。

很難理解您期望發生什么。 例如,看下面的代碼:

#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")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM