8

I have created a script in Python which notifies me at a given event. I am using the following function to produce the warning window:

def window_warn():
    '''
    This function will throw up a window with some text
    '''
    #These two lines get rid of tk root window
    root = Tkinter.Tk()
    root.withdraw()
    #tkMessageBox.deiconify() 
    TkMessageBox.showwarning("New Case", "You have a new case\n Please restart pycheck")
    return

The window draws fine, but when I click ok, the window stays in place with the button depressed. Im using xfce. Is there anyway to get the window to close after ok is clicked?

A comment indicated this may be to do with surrounding code, so for completeness:

print "Just started newcase check"
while True:
    if "Uncommitted" in webpage:
        print "oh look, 'Uncommitted' is in the url returned from the last function"
        #If this hits we call a notification window
        window_warn()
        print "sleeping"
        time.sleep(10)

        webpage = scrape_page()
    else:
        print "nothing"
        time.sleep(20)
        webpage = scrape_page()
4

5 回答 5

9

root.update()在从函数返回之前尝试调用。这将处理所有未决的 Tk/X 窗口事件。

(理想情况下,您应该在显示窗口之前建立一个主事件循环,但这假设您的整个程序都是事件驱动的,这可能并不总是有效。)

于 2013-07-21T22:05:03.480 回答
0

代码中的一个问题是每次调用函数时都会创建一个新的 Tk 元素window_warn。这可能不是您的问题的原因,但创建多个 Tk 元素是一种应该避免的不良做法。例如,在开头初始化根元素,只保留对 的调用showwarning

root = Tkinter.Tk()
root.withdraw()

def window_warn():
    '''This function will throw up a window with some text'''
    tkMessageBox.showwarning("New Case", "You have a new case\n Please restart pycheck")
    return

print "Just started newcase check"
while True:
    # ...
于 2013-07-19T15:21:24.437 回答
0

您必须调用root.mainloop()以使程序能够响应事件。

于 2013-07-17T11:15:28.833 回答
0

另一种解决方案是跟踪是否tk.messagebox已经发生,如果它刚刚中断/继续/通过以跳过重新发生的tk.messagebox

Flag = False
if Flag: 
    messagebox.showerror("Error", "Your massage here.")
    Flag = True
else:
    break

我提出这个是因为我对 StackOverflow 上提出的其他解决方案有疑问,因为我没有专门的root.mainloop()但只有self.mainloop()在课堂上Root()

我的根看起来像这样,按摩事件是在一些内部类中生成的,我无法访问 self.root:

    class Root(tk.Tk):
        def __init__(self):
            tk.Tk.__init__(self)
            ....
            class 1..
            class 2..
            self.mainloop()
于 2018-03-30T12:09:06.407 回答
0

我是这样做的:

import Tkinter as tk
import tkMessageBox
root = tk.Tk()
root.withdraw()
t = tkMessageBox.askyesno ('Title','Are you sure?')
if t:
    print("Great!!!")
    root.update()
else:
    print("Why?")
    root.update()
于 2018-02-28T12:27:01.393 回答