tkinter'Tk().after()'方法导致gui不在

2024-10-05 13:19:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着每秒钟在文本框中发一条短信。关于如何使用Tk().after()方法实现这一点,我发现了一些解释。比如这个例子

root = Tk()
def foo():
    print(repeat)
    root.after(5000, foo())

foo()
root.mainloop()

但是,尝试此解决方案时,不会出现主窗口。它也不会异常退出。我唯一能想到的是,在到达mainloop调用之前,我正在进入一个无限循环。你知道吗

这是我代码的浓缩版本

def vp_start_gui():
    global val, w, root
    root = Tk()
    top = MainWindow (root)
    init(root, top)
    root.mainloop()

class MainWindow():
    def __init__():
        self.widgets

def init(top, gui, *args, **kwargs):
    global w, top_level, root
    w = gui
    top_level = top
    root = top
    root.after(15000,updateLoans(w, root))

def updateLoans(w, rt):
    w.LoanOfferView.insert(END, viewModel.loanOffers())
    w.LoanDemandView.insert(END, viewModel.loanDemands())
    rt.after(15000,updateLoans(rt))

vp_start_gui()

viewModel是第三个模块,它从API中提取非常少量的数据。`LoanDemands是一个滚动文本小部件。你知道吗

有人知道哪里出了问题吗?你知道吗

Python3.4 使用“页面”gui设计器开发tkinter用户界面


Tags: fooinittopdefguirootglobalstart
2条回答

所以我自己找到了这个问题的答案。你知道吗

不起作用的代码示例

root = Tk()
def foo():
    print(repeat)
    root.after(5000, foo())

foo()
root.mainloop()

对我有用的代码

root = Tk()
def foo():
    print(repeat)
    root.after(5000, foo)

foo()
root.mainloop()

在仔细查看了我在底部引用的关于effbot的this SO answerthis rasperri pi forum answer和tkinter文档之后。我意识到函数名被引用了,但是函数本身并没有在after()方法中被调用

Registers an alarm callback that is called after a given time.

This method registers a callback function that will be called after a given number of milliseconds. Tkinter only guarantees that the callback will not be called earlier than that; if the system is busy, the actual delay may be much longer.

The callback is only called once for each call to this method. To keep calling the callback, you need to reregister the callback inside itself:

class App: def init(self, master): self.master = master self.poll() # start polling

def poll(self):
    ... do something ...
    self.master.after(100, self.poll)

在进入无限循环之前,程序需要等待一些东西。试试这个:

Button(root, text='start', command=foo).pack()

也请更换您的线路:

foo()

此外,将函数传递给其他函数时不应使用括号:

root.after(5000, foo)

相关问题 更多 >

    热门问题