2017-08-07 162 views
1

如何在第二個函數內更改第一個函數內部的變量值?從另一個函數改變函數內部的變量

這是我到目前爲止所提出的。 我想添加或減去1: self.num = 0

但它不加或減。

from tkinter import * 


class Application(): 
    def __init__(self, master): 
     print("Initialization") 

     self.frame = Frame(master, width=800, height=600) 
     self.frame.pack() 

     # I want to initialize self.num as 0 
     self.num = 0 

     # Call calc funtion 
     self.calc() 

    def calc(self): 
     # Subtract number 
     self.subButton = Button(self.frame, text="-", command=self.subNum) 
     self.subButton.grid(row=0, column=0) 

     # Add number 
     self.addButton = Button(self.frame, text="+", command=self.addNum) 
     self.addButton.grid(row=0, column=2) 

     # Display the number 
     self.numText = Label(self.frame, text=self.num) 
     self.numText.grid(row=0, column=1) 

     # Break mainloop. Quit Program 
     self.quitButton = Button(self.frame, text="Quit", command=self.frame.quit) 
     self.quitButton.grid(row=3, column=0) 

    # Here I add 1 to self.num 
    def addNum(self): 
     self.num += 1 
     print("Add") 
    # Here I subtract 1 from self.num 
    def subNum(self): 
     self.num -= 1 
     print("Subtract") 


root = Tk() 
app = Application(root) 
root.mainloop() 

回答

4

您正在更改self.num的值,但您並未更改標籤的文本。

您可以使用IntVar並看到它自動更改,或者您可以自己手動更改它。我個人更喜歡IntVar在這種情況下。

class Application(): 
    def __init__(self, master): 
     self.num = IntVar(value=0) 

    def calc(self): 
     .... 
     self.numText = Label(self.frame, textvariable=self.num) 
     #use textvariable instead of text option 

    def addNum(self): 
     #to change value, you should use set/get methods of IntVar 
     self.num.set(self.num.get() + 1) 

如果你不想使用IntVar(),您可以使用

def addNum(self): 
    self.num += 1 
    self.numText["text"] = self.num 
    #or 
    #self.numText.config(text=self.num) 
    print("Add") 
+1

這工作完美:) 我試過這兩種方法,我不喜歡使用IntVar,因爲它看起來不那麼「雜亂」。 謝謝。 –

1

的問題是,標籤不改變,不變量。如果你想更新你的標籤,你需要使用textvariable屬性,並在你的課堂上初始化tkinter的IntVar。以下是如何完成的:

def __init__(self, master): 
    print("Initialization") 

    self.frame = Frame(master, width=800, height=600) 
    self.frame.pack() 

    # I want to initialize self.num as 0 
    self.num = IntVar() 

    # Call calc funtion 
    self.calc() 

請注意self.num的聲明。

其次,這裏的標籤應該如何聲明:

self.numText = Label(self.frame, textvariable=self.num) 
    self.numText.grid(row=0, column=1) 

現在,要修改IntVar,你應該使用其get()set()方法,因爲你不能簡單地將值分配給它:

# Here I add 1 to self.num 
def addNum(self): 
    self.num.set(self.num.get() + 1) 
    print("Add") 
# Here I subtract 1 from self.num 
def subNum(self): 
    self.num.set(self.num.get() - 1) 
    print("Subtract") 

你可以閱讀更多關於tkinter的變量類here

相關問題