我试图把一个图形用户界面,将读取一个不断更新的TXT文件,并每隔一段时间更新。到目前为止,我成功地完成了第一部分,但我没有使用'根.after()'来循环整个过程,但会导致NameError:
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
编辑: 当更改为“推荐”时自我介绍(1000,self.get\u文本)““
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编写的程序(不仅如此),因此如果您能更明确地给出您的答案,我将不胜感激(例如,当指出缩进错误时,请参考准确的代码行)。你知道吗
首先,就像James评论的那样,应该修正缩进,使函数成为类的一部分。你知道吗
那么,换这条线
为了这个
查看以下问题的答案,它使用了我刚才给你的代码: Tkinter, executing functions over time
因为
get_text
是App
类的方法,所以应该将其称为self.get_text
。你知道吗After是一种tkinter方法。在这种情况下,您应该称之为
root.after
。自我指的是你所在的班级。因为get_text是当前类的一个方法,所以您应该使用self
调用is,这在其他编程语言(如Java)中是这样的。你知道吗相关问题 更多 >
编程相关推荐