[英]GUI programming using Tkinter Python
我有一個Tkinter GUI,具有2個輸入字段,2個按鈕(這些初始化未在代碼中顯示)。 還有一個按鈕(在代碼中初始化),該按鈕執行對兩個圖像執行更改檢測的主要任務。 還有一個進度條。
現在,完成更改檢測任務后,我想在單獨的Tkinter窗口中顯示wave.changedetection()
返回的4張圖像(pre,post,aligned,chng)。 我希望新窗口僅在changedetection()
完成后出現。( wave.py
是我自己的文件,而不是某些模塊)
不幸的是,如果在wave.changedetection()
調用之后嘗試添加代碼以創建新窗口Tk.Toplevel()
,則什么也沒有發生,並且主GUI窗口變得無響應,必須被殺死。
無法知道新創建的線程( start_thread
) start_thread
完成工作,因此我可以在那里執行Tk.Toplevel()
。
我該怎么做?
class GUI(Tkinter.Tk):
def __init__(self, parent)
Tkinter.Tk.__init__(self, parent)
self.parent = parent
self.initialize()
def initialize(self):
self.button = Tkinter.Button(text = "Start")
self.button.bind('<Button-1>', self.OnButtonClick)
self.button.pack()
self.int = Tkinter.IntVar()
self.pgbar = Tkinter.ProgressBar(variable = self.int, mode = determinate)
def OnButtonClick(self,event):
#this func has been made since I have more buttons.It may seem redundant here
self.button['command'] = self.start_thread()
self.update_idletasks()
def start_thread(self):
self.int_var.set(1)
q = queue.Queue()
self.secondary_thread = threading.Thread(target = self.change)
self.secondary_thread.start()
self.after(50, self.check_queue, q)
def check_queue(self, q):
while True:
try:
x = wave.q.get_nowait()
except queue.Empty :
self.after(50,self.check_queue,q)
break
else:
self.int_var.set(x)
if x == 6:
self.button3['state'] = 'normal'
break
def change(self):
'''The 6 functions of wave.changedetection() change the value of self.int
due to which progress bar progresses.'''
pre, post, aligned, chng = wave.changedetection(self.entry_1.get(),
self.entry_2.get())
if __name__ == '__main__':
gui = GUI(None)
gui.mainloop()
代碼以更新從此處獲取的進度條(第二個答案,誠實的安倍的答案)
您必須能夠區分名稱空間,即,這在主窗口中,並且在頂層中。 我建議您首先讓頂級工作,然后再決定是否要添加線程。 下面的代碼是創建頂級的簡單示例,並顯示了如何將小部件放置在特定的名稱空間(在本例中為窗口)。 如果有些功能要與每個Toplevel的命名空間相關聯,則可能需要也可能不需要單獨的“創建Toplevel”類。 網上也有使用Tkinter的“之后”更新進度條的示例。 這是一個不同的問題,因此,如果您對進度條有疑問,請啟動另一個線程。
try:
import Tkinter as tk ## Python 2.x
except ImportError:
import tkinter as tk ## Python 3.x
from functools import partial
class OpenToplevels():
""" open and close additional Toplevels with a button
"""
def __init__(self):
self.root = tk.Tk()
self.button_ctr=0
## in the "root" namespace *********************
but=tk.Button(self.root, text="Open a Toplevel",
command=self.open_another)
but.grid(row=0, column=0)
tk.Button(self.root, text="Exit Tkinter", bg="red",
command=self.root.quit).grid(row=1, column=0, sticky="we")
self.root.mainloop()
def close_it(self, id):
## destroy the window in this id's namespace ***********
id.destroy()
## id.withdraw()
## id.iconify()
def open_another(self):
self.button_ctr += 1
id = tk.Toplevel(self.root)
id.title("Toplevel #%d" % (self.button_ctr))
## in the "id for this Toplevel" namespace ***********
tk.Button(id, text="Close Toplevel #%d" % (self.button_ctr),
command=partial(self.close_it, id),
bg="orange", width=20).grid(row=1, column=0)
Ot=OpenToplevels()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.