我有一個python程序正在爲客戶端抓取網頁數據。 tkinter用於界面。大綱是:如何處理tkinter主循環中的錯誤?
- 窗口1讓用戶選擇要刮的信息。
- 窗口1關閉
- 刮刀啓動單獨的線程。這個線程反過來會產生更多的線程,以允許一次下載多個頁面。
- 打開窗口2以顯示下載進度(例如,「下載17的客戶端5」)
- 用戶關閉窗口2以結束程序。
程序將第一個幾百頁的工作,但隨後開始吐出錯誤消息:直到所有線程都已經停止
Traceback (most recent call last):
File "C:\Users\Me\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 248, in __del__
if self._tk.getboolean(self._tk.call("info", "exists", self._name)):
RuntimeError: main thread is not in main loop
Exception ignored in: <bound method Variable.__del__ of <tkinter.IntVar object at 0x03245510>>
多次。不知道什麼可能導致這個錯誤。實際的代碼是:
import scraper, threading
import tkinter as tk
from queue import Queue
outputQueue = Queue()
class OutputRedirect(object):
def __init__():
super().__init__()
def write(self, string):
outputQueue.put(string)
def getInformation():
stdout = sys.stdout
sys.stdout = OutputRedirect()
scraper.startThreads()
scraper.startPulling()
sys.stdout = stdout
def updateTextField(window, root):
if not outputQueue.empty():
string = outputQueue.get()
window.textArea.insert("insert", string)
outputQueue.task_done()
root.after(1, updateTextField, window, root)
'''widget/window definitions - not important'''
guiInfo = {"stuff1": [], "stuff2": []}
root = tk.Tk()
window1 = Window1(root, guiInfo)
window1.mainloop()
pullThread = threading.Thread(target=pullClaims,
args=(list(guiInfo["stuff1"]),
list(guiInfo["stuff2"])), daemon=True)
pullThread.start()
root = tk.Tk()
window2 = Window2(root)
root.after(0, updateTextField, window2, root)
window2.mainloop()
刮板程序(對自己工作正常)使用打印報表的用戶反饋。我只是將stdout指向隊列,而不是重寫所有內容。主線程使用「after」函數每秒鐘檢查隊列幾次。如果其中有任何內容,則會將其打印到窗口上的文本窗口小部件中。
我已經把代碼中的任何地方嘗試/抓住,但他們沒有抓到一件事。我確信問題出在mainloop本身,但我找不到任何有關如何在其中添加新內容的最新信息。任何幫助將不勝感激。
我看到一些失蹤進口(如'threading'),你好像一個'主循環後有東西()'調用,包括_second_'主循環()',這是隻是壞消息。 – TigerhawkT3
我的不好。這實際上是代碼的簡化版本,其中一些變量名稱已更改,並且只列出了必要的導入語句以提高可讀性。在實際的代碼中,線程被導入。此外,第二個主循環出現在第二個窗口上,並且只有在第一個窗口關閉的情況下。 – TripleD