立即学习: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()#将窗体类实例化