簡體   English   中英

為什么將函數視為全局變量

[英]Why is the function being seen as a global variable

我收到的錯誤是:未定義全局名稱'OnButtonClick2'。 我不確定程序是否將函數作為變量而不是作為函數讀取,並且我不知道該怎么做才能對其進行修復。 我同時通過了兩個參數,所以我對為什么它不起作用感到困惑。

import Tkinter

def convertDtoB(binary,left):                  
    if(left>0):                                 
        binary+=str(left%2)                     
        return convertDtoB(binary,left//2)      
    else:
        binary = int(binary[::-1])            
        return binary

def convertBtoD(decimal):                    
    answer = 0                                  
    length = len(str(decimal))                  
    decimal2 = str(decimal)[::-1]               
    for i in range(length):
        answer+=int(decimal2[i])*2**i
    return answer

class simpleapp_tk(Tkinter.Tk):
    def __init__(self,parent):
        Tkinter.Tk.__init__(self,parent)
        self.parent = parent
        self.initialize()

    def initialize(self):
        self.grid()

        self.entryVariable = Tkinter.StringVar()
        self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)

        self.button1 = Tkinter.Button(self, text="Convert Decimal to Binary", command=lambda: self.OnButtonClick(1))
        self.button1.grid(column=1,row=1)

        self.button2 = Tkinter.Button(self, text="Convert Binary to Decimal", command=lambda: self.OnButtonClick(2))
        self.button2.grid(column=1,row=2)

        self.labelVariable = Tkinter.StringVar()
        label = Tkinter.Label(self,textvariable=self.labelVariable, anchor="center", bg="white")
        label.grid(column=1,row=0,columnspan=2,sticky='')
        self.labelVariable.set("Select a conversion.")

        self.grid_columnconfigure(0,weight=1)
        self.resizable(True,False)
        self.update()
        self.geometry(self.geometry())

    def OnButtonClick2(self, button_id):
        if button_id == 3:
            binaryNumber = convertDtoB("",self.decimalNumber)
            self.labelVariable = Tkinter.StringVar()
            label_2 = Tkinter.Label(self,textvariable=self.labelVariable, anchor="center", bg="white")
            label_2.grid(column=1,row=0,columnspan=2,sticky='')
            self.label_2.set(binaryNumber)
        elif button_id == 4:
            binaryNumber = convertBtoD("",self.binaryNumber)
            self.labelVariable = Tkinter.StringVar()
            label_2 = Tkinter.Label(self,textvariable=self.labelVariable, anchor="center", bg="white")
            label_2.grid(column=1,row=0,columnspan=2,sticky='')
            self.label_2.set(binaryNumber)

    def OnButtonClick(self, button_id):
        if button_id == 1:
            self.button1.destroy()
            self.button2.destroy()
            self.entryVariable = Tkinter.StringVar()
            self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
            self.entry.grid(column=1,row=0,sticky='EW')
            self.decimalNumber = self.entryVariable.set("Enter Decimal Number Here")
            self.entry.focus_set()
            self.entry.selection_range(0, Tkinter.END)

            button3 = Tkinter.Button(self, text="Click here to convert", command=lambda: self.OnButtonClick(3))
            button3.grid(column=1,row=1)

            self.OnButtonClick2(3)

        elif button_id == 2:
            self.button1.destroy()
            self.button2.destroy()
            self.entryVariable = Tkinter.StringVar()
            self.entry = Tkinter.Entry(self,textvariable=self.entryVariable)
            self.entry.grid(column=1,row=0,sticky='EW')
            self.binaryNumber = self.entryVariable.set("Enter Binary Number Here.")
            self.entry.focus_set()
            self.entry.selection_range(0, Tkinter.END)

            button4 = Tkinter.Button(self, text="Click here to convert", command=lambda: self.OnButtonClick(4))
            button4.grid(column=1,row=1)

            self.OnButtonClick2(4)


if __name__ == "__main__":
    app = simpleapp_tk(None)
    app.title('my application')
    app.mainloop()

如果在一個類中定義這些函數,那么您對self使用很可能是不正確的,因此它們是該類的 方法/成員函數 如果是這種情況:

您應該像這樣調用方法:

self.OnButtonClick2(3)

假設這些函數是在類中定義的方法(否則您對self的使用是不正確的),那么這是在其自己的類中調用已定義方法的正確方法。

課堂信息在這里

通過使用self我假設您在課堂上。 要調用您要使用的其他類方法:

self.OnButtonClick2(3)

問題中的代碼存在一些語法問題。

  • 函數/方法沒有前導的“ def”關鍵字
  • func / method聲明后沒有縮進。

這些是函數還是類中的方法? 我問,因為第一個參數是“自我”。 使我相信這些是類中的方法。 在這種情況下,您可以執行以下方法:

self.OnButtonClick2(3)

OnButtonClick2定義為類的方法:

class simpleapp_tk(Tkinter.Tk):
    ...
    def OnButtonClick2(self, button_id):

在執行此操作時,必須通過給該函數加上基於此類的對象實例的前綴來調用此函數。 例如,要從類外部調用它,您將執行以下操作:

app = simpleapp_tk()
...
app.OnButtonClick2(...)

如果要從類中調用或引用此函數,則代碼必須引用本身,按照慣例,該自身是self 因此,要從類中調用該函數,您需要執行以下操作:

self.OnButtonClick(...)

在問題的原始版本中,代碼中有一個地方會忽略self. 部分:

OnButtonClick2(self,3)

由於OnButtonCllick2僅存在於類內部,並且由於您沒有告訴python您要使用哪個類實例來調用此函數,因此python假定您正在嘗試調用全局函數。 由於該名稱不存在全局函數,因此會給出您報告的錯誤。

解決方案應該很清楚:當您調用OnButtonClick ,從類內部進行調用時始終使用self.OnButtonClick

暫無
暫無

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

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