- Tkinter GUI Application Development Cookbook
- Alejandro Rodas de Paz
- 141字
- 2021-08-27 19:44:03
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:

推薦閱讀
- 程序員面試筆試寶典(第3版)
- Java EE框架整合開發入門到實戰:Spring+Spring MVC+MyBatis(微課版)
- 跟老齊學Python:輕松入門
- Full-Stack React Projects
- bbPress Complete
- Oracle Exadata專家手冊
- Creating Stunning Dashboards with QlikView
- Unity 2018 Shaders and Effects Cookbook
- Learning Docker Networking
- Oracle數據庫編程經典300例
- QGIS 2 Cookbook
- Visual C++從入門到精通(第2版)
- Less Web Development Cookbook
- Java EE實用教程
- Building a Media Center with Raspberry Pi