【问题标题】:Fetching a value of each Radiobutton group from n number of Radiobuttons从 n 个单选按钮中获取每个单选按钮组的值
【发布时间】:2020-06-22 18:34:33
【问题描述】:

所以我有一个场景,当必须创建“n”个独立无线电组时,我们将能够独立地检索每个无线电组的值。

当前代码为我提供了最后一个单选组的值,与我按下的按钮无关。

import tkinter # note that module name has changed from Tkinter in Python 2 to tkinter in Python 3
from tkinter import *
from tkinter import messagebox
top = tkinter.Tk()
top.title("NA")

a = int(input("Enter the number of frames"))

btn = [""]*a

def commd():
        print(i)
        print("Value changed to new value", values[i],'with value', values[i].get())
        #print('Update in value')

values = [tkinter.IntVar() for i in range(len(btn))]
print(len(values))


for i in range(len(btn)):
    print(i)
    txt = "Button_Number", (i+1)
    rtxt1 = 'Radio Button1',i+1
    rtxt2 = 'Radio Button2',i+1
    abc = Button(top, text = txt, activebackground = "Green", fg = "Blue", bg = "Red", height =5, command = aa)
    R1 = Radiobutton(top, text = "START", activebackground = "Green", fg = "Blue", bg = "Red", height = 2,variable = values[i],value=0,command = commd)
    R2 = Radiobutton(top, text = "STOP", activebackground = "Green", fg = "Blue", bg = "Red", height = 2,variable = values[i],value=1,command = commd)

    abc.grid(row = i+i, column = 0,rowspan = 2)
    R1.grid(row = i+i, column = 1)
    R2.grid(row = i+i+1,column = 1)

mainloop()

【问题讨论】:

    标签: python tkinter radio-button


    【解决方案1】:

    使用.bind(... 而不是command=... ...

    输出

    Radio Button1.0 START
    Radio Button2.1 STOP
    Radio Button1.2 START
    

    import tkinter as tk
    
    
    class App(tk.Tk):
        def __init__(self):
            super().__init__()
            self.title("NA")
    
            for i in range(3):
                print(i)
                variable = tk.StringVar()
                for n, text in enumerate(('START', 'STOP'), 1):
                    r = tk.Radiobutton(self, text=text, value=text, variable=variable)
                    r.bind('<ButtonRelease-1>', self.on_click)
                    r._group = f'Radio Button{n}.{i}'
                    r._variable = variable
                    r.grid(row=i, column=n)
    
        def on_click(self, event):
            _ = self
            w = event.widget
            print(w._group, w._variable.get())
    
    
    if __name__ == '__main__':
        App().mainloop()
    

    【讨论】:

    • 另外,请您帮忙解释一下 r._group = 'Radio Button{n}.{i}' 是如何工作的。我找不到它的参照物
    • 解释 r._group = 'Radio Button{n}.{i}' 是如何工作的。:哪一部分,左边r._grop =或者对f'Radio Button{n}.{i}',需要解释吗?
    • 实际上,我知道它是将在该实例中创建的所有按钮分组到 sam 组下,但是如何
    • @Virenmahajan 我已经更新了一个工作示例。我已经简单地改编了你的rtxt1。如果您在第一组单击START,则会打印:Radio Button1.0 STARTRadio Button1,组.0START
    猜你喜欢
    • 1970-01-01
    • 2014-04-29
    • 2017-02-06
    • 2019-10-04
    • 1970-01-01
    • 2011-03-28
    • 2022-12-06
    • 2021-12-29
    • 2013-09-04
    相关资源
    最近更新 更多