簡體   English   中英

使用“ simpledialog”時未初始化聲明的變量

[英]Declared variables not initialised when using 'simpledialog'

我一直在嘗試將變量傳遞到“ simpledialog”框的代碼上遇到問題。 但是,當我在__init__部分中聲明變量時,無法從類中的任何其他方法訪問該變量。

我創建了一個簡化的工作示例,其中我嘗試將字符串傳遞給Entry框,以便在創建“ simpledialog”時,已經填充了Entry框。 然后可以更改該值,並將新值打印到控制台。

from tkinter import *
from tkinter.simpledialog import Dialog


class App(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)
        self.parent = parent

        Button(parent, text="Press Me", command=self.run).grid()

    def run(self):
        number = "one"
        box = PopUpDialog(self, title="Example", number=number)
        print(box.values)

class PopUpDialog(Dialog):
    def __init__(self, parent, title, number, *args, **kwargs):
        Dialog.__init__(self, parent, title)
        self.number = number

    def body(self, master):
        Label(master, text="My Label: ").grid(row=0)
        self.e1 = Entry(master)
        self.e1.insert(0, self.number)  # <- This is the problem line
        self.e1.grid(row=0, column=1)

    def apply(self):
        self.values = (self.e1.get())
        return self.values

if __name__ == '__main__':
    root = Tk()
    app = App(root)
    root.mainloop()

當代碼運行並且按下“按我”按鈕時,我收到以下錯誤消息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python34\lib\tkinter\__init__.py", line 1533, in __call__
    return self.func(*args)
  File "C:/Python/scratch.py", line 14, in run
    box = PopUpDialog(self, title="Example", number=number)
  File "C:/Python/scratch.py", line 20, in __init__
    Dialog.__init__(self, parent, title)
  File "C:\Python34\lib\tkinter\simpledialog.py", line 148, in __init__
    self.initial_focus = self.body(body)
  File "C:/Python/scratch.py", line 26, in body
    self.e1.insert(0, self.number)
AttributeError: 'PopUpDialog' object has no attribute 'number'

如果我注釋掉self.e1.insert(0, self.number) ,代碼將正常工作。

關於“ simpledialog”的文檔似乎很少,我一直在使用effbot.org上的示例來嘗試了解有關對話框的更多信息。

附帶說明一下,如果我在PopUpDialog類的__init__方法中插入一條print(number)行,該數字將打印到控制台。 另外,如果我在body()方法中初始化self.number變量(例如self.number = "example" ),則代碼將按預期工作。

我敢肯定我在這里錯過了一些愚蠢的東西,但是如果您能就可能發生的事情提供任何建議,將不勝感激。

問題出在PopUpDialog類中,在函數__init__調用Dialog.__init__(self, parent, title) ,該行調用body方法。 問題是您在下一行初始化了self.number ,這就是為什么在body方法中還沒有初始化self.number的原因。

如果您切換線路,它將為您工作,就像這樣:

class PopUpDialog(Dialog):
    def __init__(self, parent, title, number, *args, **kwargs):
        self.number = number
        Dialog.__init__(self, parent, title)

編輯:

如您所見,在Dialog的__init__方法中,上面的行是:

self.initial_focus = self.body(body)調用您的body方法。

暫無
暫無

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

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