从文本文件更新Tkinter标签文本

时间:2017-03-05 15:21:27

标签: python-3.x tkinter

我有一个文件usercheck.txt,每行都有一个名字列表,所以例如我的文件看起来像这样。

Kevin
Bob
Sally
Ronnie
O'sullivan

如果有人启动Tkinter程序,他们的名字会自动添加到列表中。当它们关闭时,它们的名称会自动从文本文件中删除。我想实现一个实时更新的标签,以查看谁在线。当我尝试使用以下代码更新我的标签(这不是我的代码,但足够类似,所以我的问题很容易重现)我得到这个错误。

Traceback (most recent call last):
    File "C:\Users\Douglas Rouse\Google Drive\Python\throwaway.py", line 16, in <module>
      upd()
    File "C:\Users\Douglas Rouse\Google Drive\Python\throwaway.py", line 13, in upd
      attempt.config(d)
    File "C:\Users\Douglas Rouse\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1330, in configure
      return self._configure('configure', cnf, kw)
    File "C:\Users\Douglas Rouse\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1316, in _configure
      cnf = _cnfmerge(cnf)
    File "C:\Users\Douglas Rouse\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 100, in _cnfmerge
      for c in _flatten(cnfs):
TypeError: object of type 'builtin_function_or_method' has no len()

这是我的代码:

import tkinter as tk

root = tk.Tk()

f = open("usercheck.txt", "r").readlines()
attempt = tk.Label(root, text="\n".join(f),bg = "#42f480")
attempt.grid(row=0,column =5)

def upd():
    d = open ("usercheck.txt","r").read
    attempt.config(d)

upd()

修改 我意识到我忘记了.read()

上的括号

我得到的新错误是:

Traceback (most recent call last):
  File "C:\Users\Douglas Rouse\Google Drive\Python\throwaway.py", line 13, in <module>
        upd()
  File "C:\Users\Douglas Rouse\Google Drive\Python\throwaway.py", line 11, in upd
    attempt.config(d)
  File "C:\Users\Douglas Rouse\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1330, in configure
    return self._configure('configure', cnf, kw)
  File "C:\Users\Douglas Rouse\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1320, in _configure
    return self._getconfigure1(_flatten((self._w, cmd, '-'+cnf)))
  File "C:\Users\Douglas Rouse\AppData\Local\Programs\Python\Python35-32\lib\tkinter\__init__.py", line 1308, in _getconfigure1
    x = self.tk.splitlist(self.tk.call(*args))
tkinter.TclError: unknown option 
"-Kevin
Bob
Sally
Ronnie
O'sullivan"

1 个答案:

答案 0 :(得分:1)

函数config可用于tkinter中的许多不同小部件,它用于更改有关该小部件的内容,如宽度,高度,文本或字体,我假设您要更改标签上的文字

更改attempt.config(d)

attempt.config(text = d)