官术网_书友最值得收藏!

How to do it...

You can connect multiple Radiobutton instances using a Tkinter variable so that when you click on a non-selected option, it will deselect whatever other option was previously selected.

In the following program, we created three radio buttons for the Red, Green, and Blue options. Each time you click on a radio button, it prints the lowercase name of the corresponding color:

import tkinter as tk

COLORS = [("Red", "red"), ("Green", "green"), ("Blue", "blue")]

class ChoiceApp(tk.Tk):
    def __init__(self):
        super().__init__()
        self.var = tk.StringVar()
        self.var.set("red")
        self.buttons = [self.create_radio(c) for c in COLORS]
        for button in self.buttons:
            button.pack(anchor=tk.W, padx=10, pady=5)

    def create_radio(self, option):
        text, value = option
        return tk.Radiobutton(self, text=text, value=value, 
                              command=self.print_option, 
                              variable=self.var)

    def print_option(self):
        print(self.var.get())

if __name__ == "__main__": 
    app = ChoiceApp()
    app.mainloop()

If you run this script, it will display the application with the Red radio button already selected:

主站蜘蛛池模板: 樟树市| 图木舒克市| 桐城市| 东丽区| 道孚县| 灵宝市| 德阳市| 通山县| 蓬莱市| 乌拉特中旗| 赤峰市| 五指山市| 神农架林区| 南宁市| 临安市| 青阳县| 汉中市| 遂昌县| 库车县| 和田市| 阳谷县| 吉木萨尔县| 含山县| 永昌县| 安乡县| 二连浩特市| 浏阳市| 江华| 泰宁县| 临朐县| 长寿区| 太保市| 葫芦岛市| 韶关市| 临漳县| 德州市| 上犹县| 博罗县| 马尔康县| 东源县| 梁平县|