基本上,我创建了一个连续在无限循环中写入全局变量的线程。然后我有了应该读取并显示该变量的主机。
问题是,一旦大型机运行,它只显示它在启动时读取的变量的值,并且不会持续自我更新。如何让大型机以指定的间隔更新它的变量值?
有问题的变量称为"数据":
注意:如果您按原样运行代码,那么"数据"变量将设置为none。添加" time.sleep(5)"在执行大型机之前,将允许时间从http请求设置变量,您将看到填充的数据。
感谢您的帮助!
#!/Library/Frameworks/Python.framework/Versions/3.5/bin/python3
# -*- coding: utf-8 -*-
from tkinter import *
import time
import urllib.request
from bs4 import BeautifulSoup
import threading
from queue import Queue
data = None
class httpReq(threading.Thread):
def run(self):
global data
while True:
url = "https://twitter.com/realDonaldTrump"
page = urllib.request.urlopen(url)
soup = BeautifulSoup(page, "html.parser")
data = soup.title.text
print(data)
x = httpReq()
x.start()
class Example(Frame):
global data
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Example App")
self.pack(fill=BOTH, expand=True)
frame1 = Frame(self)
frame1.pack(fill=X)
lbl1 = Label(frame1, text="Title Data:", width= 20)
lbl1.pack(side=LEFT, padx=5, pady=5)
lbl2 = Label(frame1, text= data)
lbl2.pack(fill=X, padx=5, expand=True)
def main():
root = Tk()
root.geometry("600x200")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
答案 0 :(得分:0)
保存对标签的引用,然后设置一个更新标签的函数,然后安排自己再次调用。在以下示例中,标签将每秒更新一次。
class Example(Frame):
def __init__(self, parent):
...
# call this once, after the UI has been initialized
self.update_data()
...
def initUI(self):
...
# save a reference to the label that shows the data
self.lbl2 = Label(frame1, text= data)
self.lbl2.pack(fill=X, padx=5, expand=True)
...
def update_data(self):
# reset the label
self.lbl2.configure(text=data)
# call this function again in one second
self.lbl2.after(1000, self.update_data)