拨开荷叶行,寻梦已然成。仙女莲花里,翩翩白鹭情。
IMG-LOGO
主页 文章列表 PythonTkinker,复选框将字符串值附加到串列?

PythonTkinker,复选框将字符串值附加到串列?

白鹭 - 2022-02-16 1958 0 0

以下代码允许我在单击 tkinter 复选框时从串列中添加/洗掉 France/Italy。除了将 0 或 1 传递给 Add_France 函式,是否可以传递字符串“France”?谢谢

My_list = []

root = Tk()

Country_Variable1 = tkinter.IntVar()
Country_Variable2 = tkinter.IntVar()

def Add_France():
    if Country_Variable1.get() == 1:
        My_list.append("France")
    if Country_Variable1.get() == 0:
        My_list.remove("France")
    print (My_list)

def Add_Italy():
    if Country_Variable2.get() == 1:
        My_list.append("Italy")
    if Country_Variable2.get() == 0:
        My_list.remove("Italy")
    print (My_list)

check1 = Checkbutton(root, text='France',variable=Country_Variable1, onvalue=1, offvalue=0, command=Add_France)
check2 = Checkbutton(root, text='Italy',variable=Country_Variable2, onvalue=1, offvalue=0, command=Add_Italy)

check1.pack()
check2.pack()

root.mainloop()

uj5u.com热心网友回复:

您可以控制onvalueoffvaluewith Checkbutton,因此您可以使用它在每个状态中回传的值。在下面的示例中,您可以看到如何根据串列中的输入创建检查按钮(假设它始终是字符串串列):

from tkinter import *

root = Tk()

def process(var,text):
    try:
        val = int(var.get()) # If not selected it will give 0 as int, which will trigger `else` block
    except ValueError:
        val = var.get()

    if val: # if val is not empty, ie, if val is any selected value
        slct_ctry_lst.append(val)
    else: # if val is 0 
        slct_ctry_lst.remove(text) # Remove the corresponding text from the list

    print(slct_ctry_lst)

slct_ctry_lst = []
countries = ['France','Italy','China','Russia','India']

for idx,i in enumerate(countries):
    var = StringVar(value=" ")
    Checkbutton(root,text=i,variable=var,command=lambda i=i,var=var: process(var,i),onvalue=i).grid(row=0,column=idx)

root.mainloop()

认为这会更容易,但可能不适合ttk.Combobox

def process(e):
    val = e.widget.get()
    if val in slct_ctry_lst: # If val present inside the list
        slct_ctry_lst.remove(val) # Remove it
    else: 
        slct_ctry_lst.append(val)
    
    print(slct_ctry_lst)

slct_ctry_lst = []
countries = ['France','Italy','China','Russia','India']

cbox = ttk.Combobox(root,values=countries,state='readonly')
cbox.pack(padx=10,pady=10)
cbox.set('Select a country')

cbox.bind('<<ComboboxSelected>>',process)

uj5u.com热心网友回复:

如果此处的目标是使代码可在多个国家/地区重复使用,这是初步想法,可以进一步改进。基本上,我在lambda这里使用表达式来回呼命令函式并传递国家名称。创建了一个单独的函式来创建一个适用于所有国家的复选框。现在要将一个新国家添加到串列中,您需要做的就是将一个元素添加到available_country_list 您可以使available_country_list全域或可以将其作为自变量传递给list_countries函式。

import tkinter
from tkinter import Checkbutton

selected_country_list = []


def select_country(country_name, variable):
    global selected_country_list
    print(variable)
    if variable.get() == 1:
        selected_country_list.append(country_name)
    elif variable.get() == 0:
        selected_country_list.remove(country_name)
    print (selected_country_list)


def create_checkbox(parent, country_name):
    country_var = tkinter.IntVar()
    country_check = Checkbutton(parent, text=country_name, variable=country_var,
                                onvalue=1, offvalue=0,
                                command=lambda: select_country(country_name, country_var))
    country_check.pack()


def list_countries(root):
    available_country_list = ["France", "Italy"]
    for country in available_country_list:
        create_checkbox(root, country)


def load(root):
    # Create list of country checkboxes
    list_countries(root)


def start():
    root = tkinter.Tk()
    root.after(100, load, root)  # Enable lazy loading of your components
    root.mainloop()


if __name__ == '__main__':
    start()
标签:

0 评论

发表评论

您的电子邮件地址不会被公开。 必填的字段已做标记 *