1. 程式人生 > 實用技巧 >Python20-03_GUI程式設計----RadioButton&CheckButton

Python20-03_GUI程式設計----RadioButton&CheckButton

RadioButton&CheckButton

RadioButton單選按鈕

RadioButton控制用於選擇同一組按鈕中的一個,RadioButton可以顯示文字, 也可以顯示影象

 1 # coding:utf-8
 2 from tkinter import *
 3 from tkinter import messagebox
 4 
 5 
 6 class Application(Frame):
 7     """一個經典的GUI程式類寫法"""
 8     def __init__(self, master=None):
 9         super().__init__
(master) # super代表的是父類的定義,而不是父類的物件 10 self.master = master 11 self.pack() 12 self.createWidget() 13 14 def createWidget(self): 15 self.v = StringVar() 16 self.v.set("M") 17 18 self.r1 = Radiobutton(self, text='Xujie', value='M', variable=self.v)
19 self.r2 = Radiobutton(self, text='Liran', value='W', variable=self.v) 20 self.r1.pack(side='left') 21 self.r2.pack(side='left') 22 Button(self, text='確定', command=self.confirm).pack(side='left') 23 24 def confirm(self): 25 messagebox.showinfo('測試', '選擇主角:
'+self.v.get()) 26 27 28 29 if __name__ == "__main__": 30 root = Tk() 31 root.geometry("400x450+200+300") 32 root.title('測試') 33 app = Application(master=root) 34 root.mainloop()

Checkbutton複選按鈕

Checkbutton控制元件用於選擇多個按鈕的情況, Checkbutton可以顯示文字, 也可以顯示影象

 1 # coding:utf-8
 2 from tkinter import *
 3 from tkinter import messagebox
 4 
 5 
 6 class Application(Frame):
 7     """一個經典的GUI程式類寫法"""
 8     def __init__(self, master=None):
 9         super().__init__(master)          # super代表的是父類的定義,而不是父類的物件
10         self.master = master
11         self.pack()
12         self.createWidget()
13 
14     def createWidget(self):
15         self.man = IntVar()
16         self.woman = IntVar()
17         print(self.man.get())
18         self.c1 = Checkbutton(self, text='Xujie', variable=self.man, onvalue=1, offvalue=0)
19         self.c2 = Checkbutton(self, text='liran', variable=self.woman, onvalue=1, offvalue=0)
20         self.c1.pack(side='left')
21         self.c2.pack(side='left')
22         Button(self, text='確定', command=self.confirm).pack(side='left')
23 
24     def confirm(self):
25         if self.man.get() == 1 and self.woman.get() == 0:
26             messagebox.showinfo('你究竟喜歡誰', '原來你喜歡我啊!')
27         if self.woman.get() == 1 and self.man.get() == 0:
28             messagebox.showinfo('你究竟喜歡誰', '你居然喜歡女的!')
29         if self.woman.get() == 1 and self.man.get() == 1:
30             messagebox.showinfo('你究竟喜歡誰', '說!你到底喜歡誰!')
31         if self.man.get() == 0 and self.woman.get() == 0:
32             messagebox.showinfo('你究竟喜歡誰', '愛會消失的,對嗎?')
33 
34 
35 
36 if __name__ == "__main__":
37     root = Tk()
38     root.geometry("400x450+200+300")
39     root.title('你究竟喜歡誰?')
40     app = Application(master=root)
41     root.mainloop()