2017-06-23 249 views
0

所以我創建了一個Python Tkinter應用程序,它具有我需要每秒顯示到屏幕上的測量值。當程序運行時,值顯示,但它不更新(我在外部操縱該值,所以我知道顯示器應該改變)。如何讓顯示屏每秒動態更新?我瞭解到,我不需要爲Tkinter應用程序創建Update()方法或其他任何方法,因爲mainloop()負責處理此問題。這裏是我的代碼:Python Tkinter,每秒更新

Main.py:

from SimpleInterface import SimpleInterface 
from ADC import Converter, Differential 

adc = Converter(channelNums = [2]) 

root = SimpleInterface(adc) 
root.title = ("Test Interface") 

root.mainloop() 

SimpleInterface.py:

import tkinter as tk 
from tkinter import ttk 

class SimpleInterface(tk.Tk): 

    def __init__(self, ADC, *args, **kwargs): 
     tk.Tk.__init__(self, *args, **kwargs) 
     container = tk.Frame(self, *args, **kwargs) 
     container.grid(column = 0, row = 0, sticky = "nwes") 
     container.grid_rowconfigure(0, weight = 1) 
     container.grid_columnconfigure(0, weight = 1) 

     frame = Screen(ADC, container, self) 
     frame.grid(row = 0, column = 0, sticky = "nsew") 
     frame.tkraise() 

class Screen(tk.Frame): 

    def __init__(self, ADC, parent, controller): 
     tk.Frame.__init__(self, parent) 

     displayText = ADC.ReadValues() #this method returns a list of values 
     for i in range(len(displayText)): 
      displayText[i] = round(displayText[i], 2) 
     ttk.Label(self, text = "Test Display", background = "grey").grid(column = 7, row = 8) 
     lblTestDisplay = ttk.Label(self, text = displayText, foreground = "lime", background = "black").grid(column = 7, row = 9, sticky = "ew") 

所以正常顯示顯示displayText當代碼最初運行,但是,沒有什麼變化我手動操作正在輸入的值。我需要創建Update()方法嗎?如果是的話,我會在哪裏調用上述方法?

回答

3

是的,您將需要創建一個方法來更新值,並將該方法添加到tkinter主循環after。我建議將其命名爲其他東西,因爲update已經是tkinter方法。

由於沒有經過測試的猜測:

class Screen(tk.Frame): 
    def __init__(self, ADC, parent, controller): 
     tk.Frame.__init__(self, parent) 
     self.ADC = ADC 
     lbl = ttk.Label(self, text = "Test Display", background = "grey") 
     lbl.grid(column = 7, row = 8) 
     self.lblTestDisplay = ttk.Label(self, foreground = "lime", background = "black") 
     self.lblTestDisplay.grid(column = 7, row = 9, sticky = "ew") 

     self.adc_update() # start the adc loop 

    def adc_update(self): 
     displayText = self.ADC.ReadValues() #this method returns a list of values 
     for i in range(len(displayText)): 
      displayText[i] = round(displayText[i], 2) 
     self.lblTestDisplay.config(text = str(displayText)) # update the display 
     self.after(1000, self.adc_update) # ask the mainloop to call this method again in 1,000 milliseconds 

注意我也拆你的標籤製作成2線,一個初始化和一個佈局。你的方式非常糟糕;它會導致分配給None的變量導致錯誤。

+0

謝謝。我不知道我的初始化和佈局方式導致None變量。我將不得不記住未來。乾杯! – Skitzafreak