首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >当按钮有命令时如何导入用tkinter编写的模块

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

Stack Overflow用户
提问于 2018-09-14 10:12:34
回答 1查看 151关注 0票数 0

我希望有一个可以导入的通用Tk模块。我读过When importing modules written with tkinter and ttk, stuff doesn't work,它解释了很多,但是这个例子没有一个带有命令的按钮。

我的通用Tk模块'generic_tk_module.py‘是:

代码语言:javascript
运行
复制
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)

我的呼叫模块是:

代码语言:javascript
运行
复制
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 ()的函数调用?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-14 10:27:11

应该将close作为方法放在App类中,并在self.parent上调用destroy

代码语言:javascript
运行
复制
def close(self):           # make sure to indent to match the class indentation
    self.parent.destroy()

那么您的按钮命令应该是:

代码语言:javascript
运行
复制
command=self.close

您也应该在您的super__init__中使用App,而不是显式调用超类,但这与您的问题无关:

代码语言:javascript
运行
复制
super().__init__(parent)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52329797

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档