簡體   English   中英

如何在tkinter中綁定單選按鈕和combobox?

[英]how to bind the radio button with combobox in tkinter?

嗨,我有一些值的組合框(用戶 select 只有一個項目),我想根據 select 允許用戶從單選按鈕進行 select 多選。 例如:elemnt- 用戶 select 一個元素的組合框,然后是 select 許多作物 grom 單選按鈕。 我無法將兩者聯系起來。 請幫助我的代碼:

def calibration_window():
    global cb_elemnt,cb_crop
    top = tkinter.Toplevel (window)
    top.title ("Calibration")
    top.geometry ("400x400")
    ttk.Label (top, text="Select an element:",font = ("Segoe UI Light", 10)).grid (column=0, row=0)
    cb_elemnt = ttk.Combobox (top, values=ele_list)
    cb_elemnt.grid(column=0, row=1)
    ttk.Label (top, text="Select a crop:",font = ("Segoe UI Light", 10)).grid (column=2, row=0)
    # connect between element comobox to the func
    cb_elemnt.bind ("<<ComboboxSelected>>",set_radio)



def set_radio(event):
    i=0
    radios=[]
    for widget in radios:
        widget.destroy ()
    radios = []
    if StringVar().get() !="N":
         radio_values = pd.unique (df[df['elemnt'] == StringVar().get()]["crop"]) #take  the suitable crop from DB
    else:
        radio_values = pd.unique (df_nir[df_nir['elemnt'] == StringVar().get()]["crop"])

    for t in radio_values:
        i = i + 1
        b = Radiobutton (self, text=t, variable=IntVar(), value=t)
        b.grid (row=i, column=0)
        radios.append(b)

您應該在 function 之外創建IntVar和 list radio ,這樣它們就不會被垃圾回收。

import tkinter as tk
from tkinter import ttk
import pandas as pd
import numpy as np

#sample data
df = pd.DataFrame({"element":np.random.choice(["Elem A","Elem B","Elem C"], 20),
                   "crops": [f"Crop {i}" for i in range(20)]})

root = tk.Tk()

r_var = tk.IntVar(value=0)
radios=[]
ttk.Label(root, text="Select an element:",font=("Segoe UI Light", 10)).grid(column=0, row=0)
cb_elemnt = ttk.Combobox(root, values=df["element"].unique().tolist())
cb_elemnt.grid(column=0, row=1)
ttk.Label(root, text="Select a crop:",font=("Segoe UI Light", 10)).grid(column=2, row=0)

def set_radio(event):
    for widget in radios:
        widget.destroy()
    if cb_elemnt.get():
        radio_values = df.loc[df["element"].eq(cb_elemnt.get()),"crops"]
        for num, t in enumerate(radio_values, 1):
            b = tk.Radiobutton(root, text=t, variable=r_var, value=t)
            b.grid (row=num, column=1)
            radios.append(b)

cb_elemnt.bind ("<<ComboboxSelected>>", set_radio)
root.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM