我试图转换我之前编写的一个简单的命令行程序,以便拥有一个GUI。在开始向现有/工作代码添加内容之前,我想在Tkinter中构建GUI。我最终开始取得进展,直到让事情显示出我想要的方式,直到我得到小工具,我想让他们的显示文本根据变量的内容而改变。
从我在此处以及各种文档中阅读的内容来看,执行此操作的方法是StringVar
,我试图这样做,但是当我运行程序时, status_msg
标签小部件的文字根本不会显示。我尝试了一个set()调用来在几个地方更新变量,虽然它似乎更新了变量,但标签根本没有显示在窗口中。最后我尝试添加一个" Add Key"按钮调用强制设置调用并尝试使标签显示,但它仍然无法正常工作,尽管它确实打印出了我对控制台的期望。
我无法弄清楚我做错了什么。这是我的代码:
import tkinter as tk
numkeys = 0
keystring = str(numkeys) + " entries ready for parsing"
class Application(tk.Frame):
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def createWidgets(self):
self.numkeys = tk.StringVar()
self.numkeys.set(keystring)
api_frame = tk.LabelFrame(self, text="Key Entry", padx = 5, pady = 5)
api_frame.grid(padx = 10, pady = 10)
key1_lbl = tk.Label(api_frame, text = "Entry 1:", anchor = tk.W)
key1_lbl.grid(row = 0, column = 0)
self.key = tk.Entry(api_frame, width = 18)
self.key.grid(row = 0, column = 1)
key2_lbl = tk.Label(api_frame, text="Entry 2:")
key2_lbl.grid(row = 0, column = 2, padx = 5)
self.key2 = tk.Entry(api_frame, width = 45)
self.key2.grid(row = 0, column = 3, padx = 2, columnspan = 3)
status_msg = tk.Label(api_frame, textvariable = self.numkeys.get())
status_msg.grid(row = 1, column = 0, columnspan = 3)
btn_submit = tk.Button(api_frame, text="Add Key", width = 12, command = self.test)
btn_submit.grid(row = 1, column = 4, pady = 5)
btn_start = tk.Button(api_frame, text="Parse Keys", width = 12, command = None)
btn_start.grid(row = 1, column = 5, pady = 5)
#self.numkeys.set(keystring)
def test(self):
self.numkeys.set(keystring)
root.update_idletasks()
print("test function ran")
print(app.numkeys.get())
root = tk.Tk()
app = Application(master=root)
app.master.title('Tk test')
app.mainloop()
答案 0 :(得分:1)
替换
textvariable = self.numkeys.get()
通过
textvariable = self.numkeys