【发布时间】:2016-07-28 08:50:39
【问题描述】:
基本上,我创建了一个线程,它在无限循环中连续写入一个全局变量。然后我有了应该读取并显示该变量的大型机。
问题是主机一旦运行,只显示启动时读取的变量值,并不会不断更新自己。如何让大型机以指定的时间间隔更新其变量值?
有问题的变量称为“数据”:
注意:如果您按原样运行代码,“数据”变量将设置为无。在执行大型机之前添加“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()
【问题讨论】:
标签: python multithreading python-3.x tkinter