0
我試圖轉換我以前寫過的一個簡單的命令行程序來創建GUI。在開始將事物添加到我的現有/工作代碼之前,我想玩弄在Tkinter中構建GUI。我終於開始取得進展,只要讓事情顯示我希望他們如何,直到我得到的小部件,我希望他們的顯示文本取決於變量的內容變化。Python - Tkinter - 來自StringVar的標籤文本不會顯示/更新
從我在這裏閱讀的文檔以及各種文檔集中,要做到這一點的方法是我試圖做的StringVar
,但是當我運行程序時,status_msg
標籤小部件的文本根本沒有出現。我嘗試過在一些地方放置一個set()調用來更新變量,當它看起來更新變量時,標籤並沒有顯示在窗口中。最後,我嘗試添加一個「添加鍵」按鈕調用的函數來強制設置調用,並嘗試使標籤顯示,但它仍然不起作用,儘管它確實打印了我期望的控制檯。
我搞不清楚我做錯了什麼。這裏是我的代碼:
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()
也做了更換
!在看到這是多麼簡單之後,我感到有點愚蠢,但非常抱怨。謝謝! – Prodigal