我正在嘗試組合一個可以從連續更新的TXT文件讀取並每隔一段時間更新一次的GUI。到目前爲止,我成功地與第一部分,我沒有使用「root.after()」循環整個事情,但它會導致NameError:root.after找不到function_name
import tkinter as tk
root = tk.Tk()
class App:
def __init__(self, root):
frame = tk.Frame(root)
frame.pack()
iAutoInEN = 0
iAvailableEN = 0
self.tkAutoInEN = tk.StringVar()
self.tkAutoInEN.set(iAutoInEN)
self.tbAutoInEN = tk.Label(root, textvariable=self.tkAutoInEN)
self.tbAutoInEN.pack(side=tk.LEFT)
self.button = tk.Button(frame, text="Start", fg="red",
command=self.get_text)
self.button.pack(side=tk.LEFT)
def get_text(self):
fText = open("report.txt") #open a text file in the same folder
sContents = fText.read() #read the contents
fText.close()
# omitted working code that parses the text to lines and lines
# to items and marks them with numbers based on which they are
# allocated to a variable
if iLineCounter == 1 and iItemCounter == 3:
iAutoInEN = int(sItem)
self.tkAutoInEN.set(iAutoInEN)
root.after(1000,root,get_text(self))
app = App(root)
root.mainloop()
try:
root.destroy() # optional; see description below
except:
pass
一審沒有任何問題,運行,更新值從0到在TXT文件中的號碼,但伴隨着的錯誤
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\...\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:/.../pythonlab/GUI3.py", line 117, in get_text
self.after(1000,root,get_text())
NameError: name 'get_text' is not defined
編輯: 當變爲推薦 「self.after(1000,self.get_text)」
class App:
...
def get_text(self):
fText = open("report.txt") #open a text file in the same folder
sContents = fText.read() #read the contents
fText.close()
# omitted code
if iLineCounter == 1 and iItemCounter == 3:
iAutoInEN = int(sItem)
self.tkAutoInEN.set(iAutoInEN)
self.after(1000,self.get_text)
誤差變化
Traceback (most recent call last):
File "C:/.../pythonlab/GUI3.py", line 6, in <module>
class App:
File "C:/.../pythonlab/GUI3.py", line 117, in App
self.after(1000, self.get_text)
NameError: name 'self' is not defined
也請考慮,這是我的第一個程序(不僅)在Python,所以如果你是多一點點明確的與你的答案我將不勝感激(例如當指出縮進錯誤時,請參閱確切的代碼行)。
解決您的縮進。這些方法沒有縮進,所以不屬於類。 –
謝謝 - 您指的是哪種方法?這基本上是我的第一個Python程序,我正在學習,所以我仍然很迷茫...... :) – Eleshar
特里編輯它時,縮進問題得到解決。之前,由於'init'和'get_text'函數沒有縮進,所以它們不屬於App類。應用程序類然後是無用的。請確保更改您的計算機上的代碼,以匹配問題中的編輯代碼,以避免將來出現任何問題。 – Xetnus