关于Checkbutton多选按钮将选中的文本放到一个列表里面
from tkinter import *ck = Tk()
GNLB = ['a,234', 'b,567', 'c,890']
for gnlb in GNLB:
gnxk = Checkbutton(ck,text=gnlb)
gnxk.pack()
mainloop()
怎么将选中的文本放到一个列表里面,取消时又自动删除,或者能直接把后面数字放到列表
可以这样实现,参考代码:
from tkinter import *
def check(event):
for i in values:
if values.get() and i["text"] not in result:
result.append(i["text"])
elif not values.get() and i["text"] in result:
result.remove(i["text"])
def printResult():
print(result)
ck = Tk()
result = []
GNLB = ['a,234', 'b,567', 'c,890']
values = {}
for gnlb in GNLB:
v = IntVar()
gnxk = Checkbutton(ck, variable=v, text=gnlb)
gnxk.pack()
values = v
button = Button(ck, text="打印结果列表", command=printResult)
button.pack(padx=5, pady=5)
ck.bind("<Button-1>", check)
mainloop() from tkinter import *
ck = Tk()
def test(event):
for i, b in enumerate(chk):
if b == event.widget: # 通过绑定相同的事件,在事件中判断 button 是否等于 event.widget 判断按了哪个button
print(chkVar.get())
print(chkText.get())
GNLB = ['a,234', 'b,567', 'c,890']
chkText = [] # chk的文本 StringVar
chkVar = [] # chk的选中状态 IntVar
chk = []
for i, gnlb in enumerate(GNLB):
chkText.append(StringVar())
chkText.set(gnlb)
chkVar.append(IntVar())
chkVar.set(0) # 0不选中
gnxk = Checkbutton(ck,textvariable=chkText, variable=chkVar)
gnxk.pack()
gnxk.bind("<Button-1>",test)
chk.append(gnxk)
mainloop()
Twilight6 发表于 2022-5-11 23:26
可以这样实现,参考代码:
怎样可以只把数字234 567等值放到列表呢, 如明境 发表于 2022-5-12 09:56
怎样可以只把数字234 567等值放到列表呢,
可以这样:
from tkinter import *
def check(event):
for i in values:
temp = i["text"].split(",")
if values.get() and temp not in result:
result.append(temp)
elif not values.get() and temp in result:
result.remove(temp)
def printResult():
print(result)
ck = Tk()
result = []
GNLB = ['a,234', 'b,567', 'c,890']
values = {}
for gnlb in GNLB:
v = IntVar()
gnxk = Checkbutton(ck, variable=v, text=gnlb)
gnxk.pack()
values = v
button = Button(ck, text="打印结果列表", command=printResult)
button.pack(padx=5, pady=5)
ck.bind("<Button-1>", check)
mainloop()
页:
[1]