当按钮有命令时如何导入用tkinter编写的模块

时间:2018-09-14 10:12:34

标签: tkinter

我想要一个可以导入的通用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 close()设置函数调用?

0 个答案:

没有答案