2016-07-28 8 views
0

基本的に、グローバル変数を無限ループで連続的に書き込むスレッドを作成しました。それから私はその変数を読み込んで表示するメインフレームを持っています。Python3:メインフレーム内での変数の連続更新

メインフレームが実行されると、起動時に読み取った変数の値のみが表示され、継続的に更新されないという問題があります。メインフレームに変数の値を指定した間隔で更新させるにはどうすればよいですか?

問題の変数は、「データ」と呼ばれている:

注:あなたがそのままのコードを実行した場合、「データ」変数が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

ラベルへの参照を保存し、ラベルを更新して、再度呼び出されるように設定する関数を設定します。次の例では、ラベルは1秒に1回更新されます。

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) 
+0

ありがとうブライアン、それは完璧に働いた! 。 。 。あなたが読んでお勧めするTkinterに固有のオンラインリソースはありますか? –

関連する問題