立即學習:https://edu.csdn.net/course/play/19711/343115?utm_source=blogtoedu
單選鈕:Radiobutton
?
1)相對于大部分組件而言,最大的區別在于單選鈕綁定事件是直接通過構建單選鈕時方法中的command參數來進行事件的綁定,而其他的組件一般都是通過bind函數來進行事件的綁定。
self.singlebutton = tkinter.Radiobutton(self.root,text = title,value = index,command = self.singlebutton_handle_event,#通過command給單選鈕綁定事件variable = self.status)
2)單選鈕在創建時得注意的是:含有兩個值,一個是顯示的文本值,一個是真正執行操作或者標記的值如下:
self.sex = [("男",0),("女",1)]#設置單選鈕要顯示的值以及真實操作的值
3)要想給單選鈕設置默認的選中項,則需要使用IntVar函數,該函數可以通過.set()來設置初始的索引,在創建單選鈕的參數中使variable=.set()即可,也可以通過.get來獲得當前選擇項的索引
self.status = tkinter.IntVar()#設置默認選項self.status.set(0)self.singlebutton = tkinter.Radiobutton(self.root,text = title,value = index,command = self.singlebutton_handle_event,#通過command給單選鈕綁定事件variable = self.status)index == self.status.get():
4)完整代碼
import tkinter#導入創建窗體的相關模塊
import osimage_path = r'C:\Users\jinlin\Desktop\python_further_study\GUI編程\resources' + os.sep + 'linlianqin.gif'#因為每個平臺的分隔符不一樣,所以用os.sep可以自動切換到相應平臺的分隔符class Mainwindow():#創建窗口類def __init__(self):self.root = tkinter.Tk()#創建主體窗口self.root.title('linlianqin')#定義窗體的名字self.root.geometry('500x500')#定義窗體的初始大小self.root.maxsize(1200,1200)#設置窗口可以顯示的最大尺寸self.single_button()self.root.mainloop()#顯示窗口,這個代碼一定要放在所有窗口設置的后面def single_button(self):#定義一個單選妞self.status = tkinter.IntVar()#設置默認選項self.label = tkinter.Label(self.root,text = "請選擇您的性別:")self.label.grid(row = 0,column = 0)self.sex = [("男",0),("女",1)]#設置單選鈕要顯示的值以及真實操作的值self.status.set(0)self.column = 1for title,index in self.sex:self.singlebutton = tkinter.Radiobutton(self.root,text = title,value = index,command = self.singlebutton_handle_event,#通過command給單選鈕綁定事件variable = self.status)self.singlebutton.grid(row = 0,column=self.column)self.column+=1def singlebutton_handle_event(self):#定義單選鈕的處理事件self.content = tkinter.StringVar()self.label = tkinter.Label(self.root,textvariable = self.content)for title,index in self.sex:if index == self.status.get():self.content.set("您選擇的性別是%s"%title)self.label.grid(row = 1,column = 0)if __name__ == '__main__':Mainwindow()#將窗體類實例化
?