這裏有一些問題的背景:我目前正在嘗試在樹莓派上顯示一個簡單的tkinter gui來顯示溫度計/溼度傳感器的傳感器讀數。然而,在我開始之前,我需要檢查是否可以讓tkinter用新值更新自己。我已經包含了我正在使用的代碼。現在,我試圖通過使用root.after以root.after調用change(),它會更新gui中的某個標籤,而代碼位於root.mainloop()中,以攝氏溫度爲單位每秒增加1。 )。但是,每次嘗試時都會遇到錯誤,我不確定如何解決此問題。在root.after()上工作時遇到問題
我的代碼:
import tkinter as tk
from tkinter import ttk
class Example(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, background="white")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Interface")
self.style = ttk.Style()
self.style.theme_use("alt")
self.pack(fill=tk.BOTH, expand=1)
self.tempLabel = tk.Label(self, text="Temperature", fg="black", bg="white")
self.tempLabel.grid(row=0, column=0)
self.tempC = tk.Label(self, text="4654645˚ Celsius", fg="black", bg="white")
self.tempC.grid(row=1, column=0)
self.tempF = tk.Label(self, text="0˚ Fahrenheit", fg="black", bg="white")
self.tempF.grid(row=2, column=0)
self.rhLabel = tk.Label(self, text="Relative Humidity", fg="black", bg ="white")
self.rhLabel.grid(row=0, column=1)
self.rh = tk.Label(self, text=" 53.37%", fg="black", bg="white")
self.rh.grid(row=1, column=1)
def change (self, variable, state):
variable + 1
newText = str(variable)
if state ==1:
newText += "%"
self.rh.config(text=newText, width =20)
self.rh.update_idletasks()
elif state ==2:
newText += "˚ Celsius"
self.tempC.config(text=newText, width =20)
self.tempC.update_idletasks()
elif state ==3:
newText += "˚ Fahrenheit"
self.tempF.config(text=newText, width =20)
self.tempF.update_idletasks()
self.after(1000, self.change)
def main():
var =0
root = tk.Tk()
root.geometry("250x250+300+300")
app = Example(root)
app.change(var, 2)
root.mainloop()
if __name__ == '__main__':
main()
這裏是我的錯誤:(此錯誤是固定的)
Traceback (most recent call last):
File "/home/pi/tkinter_test.py", line 108, in <module>
main()
File "/home/pi/tkinter_test.py", line 102, in main
app.change(var, 2)
File "/home/pi/tkinter_test.py", line 92, in change
tk.Frame.after(1000, self.change)
File "/usr/lib/python3.2/tkinter/__init__.py", line 486, in after
self.tk.call('after', ms)
AttributeError: 'int' object has no attribute 'tk'
任何幫助,將不勝感激。我是python的新手,所以代碼中的問題可能很愚蠢。
編輯:
每低於凱文的建議下,我改變tk.Frame.after(1000,self.change)到self.after(1000,self.change)。不過,我現在收到此錯誤:
Exception in Tkinter callback
Traceback (most recent call last):
File "/usr/lib/python3.2/tkinter/__init__.py", line 1426, in __call__
return self.func(*args)
File "/usr/lib/python3.2/tkinter/__init__.py", line 490, in callit
func(*args)
TypeError: change() takes exactly 3 arguments (1 given)
它似乎不喜歡我叫self.change不帶任何參數,當我在以後使用它()。然而,在網上查找我從來沒有看到在after()中給出模塊的參數,並且當我添加它們時,我得到遞歸錯誤。
我不認爲你可以調用'之後'沒有提供小部件實例。您可以在'main'中執行'root.after'或在'change'執行'self.after',但不能只執行'tk.Frame.after'。 (我發佈這個評論,而不是一個答案,因爲我認爲在此之前,你會遇到一些其他問題,然後你的代碼完美工作,我沒有時間來解決它們) – Kevin
是的,使用self.root得到gui出現(但不更新),並出現另一個錯誤。感謝您的修復。我會盡力去解決這個新錯誤,但如果我失敗了,我會把它添加到上面的帖子中。 – Keenan
閱讀錯誤消息:它告訴你到底發生了什麼問題。你設計了'change'以用參數調用,但是當你調用'after'後面的時候你沒有傳遞那些參數。 –