如何解决tkinter:由于 TKinter 中的单独进程,如何正确更新 GUI?
我正在尝试用 TKinter 和 selenium 编写一个 Python 程序,它检查互联网连接,如果没有互联网连接,它会转到我的互联网提供商的特定页面并输入我的登录名和密码(我需要这个,因为互联网每 30 分钟不活动就会断开连接)。
所以我试图用 tkinter 同时做多个事情,我目前需要的是一个功能,它根据互联网是否连接每 100 毫秒更新一次 GUI。这基本上是互联网连接状态的可视化。
import tkinter as tk
import urllib.request
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
DRIVER_PATH = 'C:/chromedriver.exe'
STATE = False
URL = 'URL ADRESS OF LOGIN PAGE OF MY PROVIDER'
def _selenium_driver():
#your login and password information
LOGIN = "login"
PASSWORD = "password"
#option not to open a chrome window,and run
#the app in background instead
options = webdriver.ChromeOptions()
options.add_argument("headless")
#start the Chrome Driver,and access URL
driver = webdriver.Chrome(options=options,executable_path=DRIVER_PATH)
driver.get(URL)
#find the appropriate fields by name and fill
#in with data. Names can be found by inspecting
#elements by right-clicking the element in chrome
login = driver.find_element_by_name("loginid")
login.send_keys(LOGIN)
pswd = driver.find_element_by_name("password")
pswd.send_keys(PASSWORD)
login.send_keys(Keys.RETURN)
driver.quit()
def isInterneton():
# tries opening google IP address,# returns false if unsuccessful
try:
urllib.request.urlopen('http://216.58.192.142',timeout=1)
return True
except urllib.request.URLError as err:
return False
def updateConnectionStatus(tk,root,canvas):
print('is in updateConnectionStatus')
if isInterneton():
label1 = tk.Label(root,text= "Connected")
canvas.create_window(160,190,window=label1)
elif not isInterneton():
label1 = tk.Label(root,text= "Reconnecting")
canvas.create_window(160,window=label1)
root.after(100,updateConnectionStatus(tk,canvas))
root= tk.Tk()
canvas1 = tk.Canvas(root,width = 300,height = 250)
canvas1.pack()
root.mainloop()
root.after(100,canvas1))
这段代码的问题是它只在最后一行输入'root.after',在我关闭窗口之后,所以基本上是在主循环完成之后。我怎样才能让它在后台自动总是检查连接并更新状态?
解决方法
将 root.mainloop()
行移到文件底部。
您还需要在倒数第二行和函数中使用正确的调用,如下所示:
root.after(100,updateConnectionStatus,tk,root,canvas1)
您还应该更新标签,而不是每次都创建一个新标签。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。