效果展示:
默認選擇第一項,並顯示“you have selected A”
當點擊Option B或者Option C時,頂上的文字跟隨變化
import tkinter as tk # 定義窗口 window = tk.Tk() window.title('my window') # 窗口title window.geometry('350x300') # 窗口尺寸 # 定義Label l = tk.Label(window, bg="yellow", width=20,text='you have selected A') l.pack() def print_selection(): # 改變L參數,r_value.get()獲取共享變量的值 l.config(text='you have selected ' + r_value.get()) # 定義Radiobutton ''' text 代表顯示的文字 variable,value表示,當被選中時,將value的值,賦值給variable variable可以理解為同一個組中與其他radiobutton的共享變量 ''' r_value = tk.StringVar()
# 默認顯示A選項 r_value.set('A') r1 = tk.Radiobutton(window, text='Option A', variable=r_value, value='A', command=print_selection) r1.pack() r2 = tk.Radiobutton(window, text='Option B', variable=r_value, value='B', command=print_selection) r2.pack() r3 = tk.Radiobutton(window, text='Option C', variable=r_value, value='C', command=print_selection) r3.pack() window.mainloop()
總結:
1.這三個RadioButton都是在一個組內,所以每次只能選擇一個
2.變量r_value相當於一個組內的共享變量,選中一個item后,會把value的值賦予共享變量variable
3.r_value.set(),設置默認值
4.r_value.get(),獲取選中的值