這幾天某同學遇到了一個棘手的問題,困擾了很久。今天終於解決了,我來記錄一下坑。
情景:python 使用tkinter為第二層窗體(頂層窗體)中的一個輸入框設定默認值時,總是無法設置,而且對輸入框獲取值,也是空的。沒有報錯。
解決辦法:只需要頂層窗體使用Toplevel,其余代碼不變就可以解決。(toplevel本就在tkinter庫當中,不需要引入,只需要將上層窗體由tk.Tk()改用tk.Toplevel()即可)
代碼示例:底層窗口一個按鈕,打開新窗口(頂層窗口),新窗口輸入框顯示默認值,輸入新值,獲取新值。
import tkinter as tk # 設置根(底層)窗口 window = tk.Tk() window.title('根窗口') window.geometry('500x300') # 傳值變量 textVar = tk.StringVar() textVar.set('在這里輸入...') # 獲取新窗口中輸入框的數據 def getText(): global textVar text = textVar.get() print(text) # 創建新窗口 def create_toplevel(): # 新窗口(頂層窗口),使用Toplevel top = tk.Toplevel() top.title('打開新窗口') top.geometry('400x200') textInput = tk.Entry(top, bd=10, textvariable=textVar) textInput.pack() # 獲取值的按鈕 getInputTextBtn = tk.Button(top, text="獲取值", font=16, bg="silver", relief='groove', command=getText).place(x=150, y=120) top.mainloop() # 打開新窗口 openNewWindowBtn = tk.Button(window, text='打開新窗口', font=16, bg="silver", relief='groove', height=2, width=28, command=create_toplevel).pack() window.mainloop()
效果:
PS:頁面放大食用更佳。