我想在頂層視窗中的文本框中插入一個文本,但我希望它取決于一個復選框是否選中。例如,如果選中復選框,則文本框將顯示蘋果,否則應顯示橙色。我在 check_checkbox 函式中添加了 print 以查看它是否有問題,它似乎正在作業,但我無法讓它出現在文本框中。
from tkinter import ttk
import tkinter.scrolledtext as st
root = tk.Tk()
root.geometry("100x100")
root.title("Test")
def check_checkbox():
if isChecked.get() == 1:
testVar = tk.StringVar(root, "apple")
else:
testVar = tk.StringVar(root, "orange")
print(testVar.get())
def new_win(testVar):
win = tk.Toplevel(root)
win.geometry("100x100")
win.title("Test 2")
win_txt_box = st.ScrolledText(win, height=50, width=50)
win_txt_box.pack()
win_txt_box.insert("1.0", f"" testVar "")
return;
testVar = tk.StringVar()
isChecked = tk.IntVar()
# checkbox
check_box = ttk.Checkbutton(root, text="CHECK THIS",
command=check_checkbox,
variable=isChecked,
onvalue=1,
offvalue=0,)
check_box.grid(column=0, row=0)
# button
test_button = ttk.Button(root, text="CLICK THIS", command=lambda: new_win(testVar.get()))
test_button.grid(column=0, row=1)
root.mainloop()```
uj5u.com熱心網友回復:
添加一個全域內部函式。第 13、18 和 28 行只有三個變化。
def check_checkbox():
global x
if isChecked.get() == 1:
testVar = tk.StringVar(root, "apple")
else:
testVar = tk.StringVar(root, "orange")
x = (testVar.get())
def new_win(testVar):
win = tk.Toplevel(root)
win.geometry("100x100")
win.title("Test 2")
win_txt_box = st.ScrolledText(win, height=50, width=50)
win_txt_box.pack()
win_txt_box.insert("1.0", x)
return
結果:
]
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519568.html
標籤:功能变量tkinter
