1.框架一
from tkinter import * # Import tkinter
class WidgetsDemo:
def __init__(self):
window = Tk() # Create a window
window.title("我是小工具的標題") # Set a title
# Add a button, a check button, and a radio button to frame1
frame1 = Frame(window) # Create and add a frame to window
frame1.pack() # 設定框架1(frame1)的位置
self.v1 = IntVar() #核取方塊的變數類型是整數0與1,設定類別中變數v1為整數類型
cbtBold = Checkbutton(frame1, text = "Bold", variable = self.v1, command = self.processCheckbutton)
self.v2 = IntVar() #多選一按鈕的變數類型是整數1、2、3,設定類別中變數v2為整數類型
rbRed = Radiobutton(frame1, text = "Red", bg = "red", variable = self.v2, value = 1, command = self.processRadiobutton)
rbYellow = Radiobutton(frame1, text = "Yellow", bg = "yellow", variable = self.v2, value = 2, command = self.processRadiobutton)
cbtBold.grid(row = 1, column = 1) # 設定核取方塊的位置在第1列第1欄
rbRed.grid(row = 1, column = 2) # 設定多選一按鈕的位置在第1列第2欄
rbYellow.grid(row = 1, column = 3) # 設定多選一按鈕的位置在第1列第3欄
# Add a button, a check button, and a radio button to frame1
frame2 = Frame(window) # Create and add a frame to window
frame2.pack() # 設定框架2(frame2)的位置
label = Label(frame2, text = "輸入你的名字: ")
self.name = StringVar() #輸入欄位的變數類型是字串,設定類別中變數v1為字串類型
entryName = Entry(frame2, textvariable = self.name)
btGetName = Button(frame2, text = "按鈕獲取你的名字", command = self.processButton)
message = Message(frame2, text = "這是測試版的小工具,不要慌張")
label.grid(row = 1, column = 1) # 設定label位置在第1列第1欄
entryName.grid(row = 1, column = 2) # 設定entryName位置在第1列第2欄
btGetName.grid(row = 1, column = 3) # 設定btGetName位置在第1列第3欄
message.grid(row = 1, column = 4) # 設定message位置在第1列第4欄
# Add a text
text = Text(window) # Create a text add to the window
text.pack()
text.insert(END, "Tip\nThe best way to learn Tkinter is to read ") #可以加上換行符號/n 使文字視窗的文字換行
text.insert(END, "these carefully designed examples and use them ")
text.insert(END, "to create your applications.")
window.mainloop() # Create an event loop
def processCheckbutton(self):
print("check button is " + ("checked " if self.v1.get() == 1 else "unchecked"))
def processRadiobutton(self):
print(("Red" if self.v2.get() == 1 else "Yellow") + " is selected " )
def processButton(self):
print("Your name is " + self.name.get())
WidgetsDemo() # Create GUI