我希望有一个可以导入的通用Tk模块。我读过When importing modules written with tkinter and ttk, stuff doesn't work,它解释了很多,但是这个例子没有一个带有命令的按钮。
我的通用Tk模块'generic_tk_module.py‘是:
from tkinter import Tk, ttk, Text
class AppWindow(ttk.Frame):
    def __init__(self, parent):
        ttk.Frame.__init__(self, parent)   
        self.parent = parent
        self.makewidgets()
    def makewidgets(self):
        self.pack(side='top', fill='both', expand=True)
        btn_close = ttk.Button(self, text='Close', command=close)
        btn_close.grid(row=3, column=2, sticky='n', pady=4, padx=5)
        txw = Text(self)
        txw.grid(row=2, column=0, columnspan=2, rowspan=2, pady=5, padx=5, sticky=('nsew'))
        txw.configure(font=("consolas", 11), padx=20) 
        self.txw = txw
        self.columnconfigure(1, weight=1)
        self.rowconfigure(2, weight=1)
    def write(self, text):
        """Schrijf aan het einde van de tekst, en scroll eventueel."""
        self.txw.insert('end', text)
def close():
    root.destroy()
def main(window_handle):
    print("welcome message from the generic module ", file = window_handle)
    root.mainloop()
if __name__ == '__main__':
    root = Tk()
    root.geometry("700x400")
    root.update()
    window_handle = AppWindow(root)
    main(window_handle)我的呼叫模块是:
from tkinter import Tk
from generic_tk_module import AppWindow
def main():
    root = Tk()
    root.geometry("700x400")
    root.update()
    window_handle = AppWindow(root)
    print("welcome message from the calling module", file = window_handle)
    root.mainloop()
if __name__ == '__main__':
    main()当然,当单击btn_close时会发生错误:未定义名称'root‘。
如何在泛型模块中设置关闭按钮、command=close、和def ()的函数调用?
发布于 2018-09-14 10:27:11
应该将close作为方法放在App类中,并在self.parent上调用destroy
def close(self):           # make sure to indent to match the class indentation
    self.parent.destroy()那么您的按钮命令应该是:
command=self.close您也应该在您的super的__init__中使用App,而不是显式调用超类,但这与您的问题无关:
super().__init__(parent)https://stackoverflow.com/questions/52329797
复制相似问题