【问题标题】:Continue a code after calling a class method which opens a tkinter window调用打开 tkinter 窗口的类方法后继续代码
【发布时间】:2022-01-08 13:31:23
【问题描述】:

我创建了一个创建二叉树的类“节点”。 (我知道我可以使用二叉树模块,但它是 DSA 主题中给我的一个项目。)

class Node:
    def __init__(self, data) -> None:
        #initialisation

    def addNode(self, data): 
        # Code to add data.
        

    def traverse(self):
        #traverses the tree and returns a dict

    def view(
        self,
        length=500,
        width=1000,
        yDist=50,
        xDistScale=0.25,
        title='Tree View',
    ):
        # shows the tree in a tkinter window as in the screenshot attached
        tree = self.traverse()
        root = tk.Tk()
        self.root=root
        root.geometry(str(width)+'x'+str(length))
        root.title(title)

        # ........ some code which places the nodes on the window using the place() method

        root.mainloop()

现在,我将代码导入另一个文件,创建类的实例添加一些节点并调用 view() 方法它工作正常,但是 view() 方法之后的代码在我关闭 tkinter 之前不会运行窗户。 如何使 view() 之后的代码在不关闭窗口的情况下运行? 如果窗口无法更新也没关系。

我在其中导入和使用节点类的代码:

t1 = Node(15)
t1.addNode(12)
t1.addNode(27)
t1.addNode(7)
t1.addNode(14)
t1.addNode(20)
t1.addNode(88)
t1.addNode(23)

t1.view()

# The code here does not run until I close the window.

上述代码的输出: Link to image

我尝试了谷歌搜索,还查看了以下 stackoverflow 帖子:

但没有任何帮助。 请帮助/指导我。 我是 StackOverflow 和 Python 的新手。

在此先感谢 :)

【问题讨论】:

    标签: python tkinter


    【解决方案1】:

    方法一:不更新窗口
    您可以将root.mainloop() 替换为root.update()。这将停止显示对窗口的任何更改。只有在程序停止运行时,该窗口才会并始终关闭。

    方法二:使用线程
    您可以使用import threading 在另一个线程中运行t1.view()threading.Thread(target=t1.view).start()。这可能会导致 Tcl_AsyncDelete 错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多