Tkinter:从另一个模块调用应用程序功能

时间:2020-07-13 01:52:29

标签: python tkinter dynamic module widget

我创建了一个虚拟项目来举例说明我的目标是

该应用程序包含两个小部件,一个按钮和一个文本区域。按下按钮时,调用另一个模块。然后,被调用模块回调到大型机并访问“插入文本”功能,就像在被调用模块中运行的代码的日志一样。 以下是我要实现的目标的简单示例。

项目的结构为:

  • main.py

  • 另一个(文件夹)

    • module.py

main.py

from tkinter import *
import tkinter as tk
#from tkmacosx import Button ignore if not in MacOS

from another import module

class Example():
    def __init__(self,parent):
        self.main_frame = Frame(root)
        self.main_frame.pack()
        self.text = Text(self.main_frame)
        self.text.grid(row = 0, column = 0)
        self.button = Button(self.main_frame,
            height = 25,
            width = 150,
            command = self.call_another_module)
        self.button.grid(row = 1, column = 0)
        self.new_text_line("Start.")

    def call_another_module(self):
        self.new_text_line("button press!\n")
        module.Generic_class()

    def new_text_line(self, message):
        self.text.insert(INSERT, message + '\n')

if __name__ == '__main__':
    root = Tk()
    root.title("Example")
    app = Example(root)
    root.mainloop()

module.py

import tkinter as tk

#Shenanigans to import main
import os,sys,inspect
currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0,parentdir)

import main


class Generic_class():
    #code of something
    #call new_text_line function 
    main.Example().new_text_line("Hurray!")
    #continue code

我知道调用上面示例中显示的主模块是不正确的,因为我再次调用了应用实例。

非常感谢您对这个特定问题以及针对此问题的其他方法的反馈。

1 个答案:

答案 0 :(得分:0)

查看其他小部件-所有其他部件都将其他小部件作为第一个参数,并且是其父级。

与您的课堂相同-将父窗口小部件作为第一个参数

class GenericClass(): # PEP8: `UpperCaseNames` for classes

    def __init__(self, parent):
        self.parent = parent
        self.parent.new_text_line("Hurray!")

然后您可以创建它

module.GenericClass(self)

,它将可以访问Example

中的所有函数/变量