我創建了一個帶有 2 個輸入框和一個帶有滾動的復選按鈕串列(源自串列“a”)的 GUI。現在,我想顯示所有已選中的復選按鈕。
def sel(x):
selection = "You selected the option " str(x)
label.config(text = selection)
from tkinter import *
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
root = Tk()
Label(root, text='Date from (format: 01-Apr-2022)').place(x=120,y=50)
Label(root, text='Date till (format: 21-Apr-2022)').place(x=120,y=150)
e1 = Entry(root)
e2 = Entry(root)
e1.place(x=300,y=50)
e2.place(x=300, y=150)
text = ScrolledText(root, width=50, height=60)
text.pack()
label = Label(root)
label.place(x=100, y=450)
b = [IntVar() for x in a[:10]]
for i in range(len(a[:10])):
cb = tk.Checkbutton(text, text=a[i], variable=b[i], bg='white', anchor='w', onvalue = 1, offvalue = 0, command=sel(a[i]))
text.window_create('end', window=cb)
text.insert('end', '\n')
root.mainloop()
我想出了上面的代碼,但生成的 GUI(下面)沒有按預期作業。即使沒有選擇它,它也只會顯示最底部的復選按鈕。此外,選擇或取消選擇任何其他復選按鈕都沒有任何效果。

uj5u.com熱心網友回復:
使用 list 的示例串列a,因為您沒有在問題中提供它。
修復
由于您正在為函式提供引數,因此您可以使用 python lambdas。目前,您沒有將函式傳遞給 CheckButton 的 command 屬性,而是傳遞sel().
參考
- lambda 運算式
解決方案
您可以迭代 IntVar 串列并決定選擇哪些,而不是將名稱作為引數傳遞給函式。
import tkinter as tk
from tkinter.scrolledtext import ScrolledText
root = tk.Tk()
def refresh():
selected = []
for i in range(len(a)):
if b[i].get():
selected.append(a[i])
if len(selected) > 1:
label.config(text=(", ".join(selected) " are selected"))
elif len(selected) == 1:
label.config(text=(selected[0] " is selected"))
else:
label.config(text="")
tk.Label(root, text='Date from (format: 01-Apr-2022)').place(x=120,y=50)
tk.Label(root, text='Date till (format: 21-Apr-2022)').place(x=120,y=150)
e1 = tk.Entry(root)
e2 = tk.Entry(root)
e1.place(x=300,y=50)
e2.place(x=300, y=150)
text = ScrolledText(root, width=50, height=60)
text.pack()
label = tk.Label(root)
label.place(x=100, y=450)
a = ["test1", "test2", "test3", "test4"]
b = []
for i in a:
var = tk.IntVar()
b.append(var)
cb = tk.Checkbutton(text, text=i, variable=var, bg='white', anchor='w', onvalue=1, offvalue=0, command=refresh)
text.window_create('end', window=cb)
text.insert('end', '\n')
root.mainloop()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/467705.html
標籤:Python python-3.x 用户界面 tkinter
下一篇:單擊選項選單時無法更新文本框
