本博文源於python基礎,實驗由Toplevel組件來創建自定義的對話框。
實驗效果
實驗原理
設計一個自定義的對話框MyDialog與MyButton類,然後實例化加入主窗口
實驗代碼
# -*- coding:utf-8 -*-
#
import tkinter
import tkinter.messagebox
class MyDialog(object): #定義對話框類
def __init__(self, root): #對話框初始化
self.top = tkinter.Toplevel(root) #生成TopLevel組件
label = tkinter.Label(self.top, text='PLease Input') # 生成標籤組件
label.pack()
self.entry = tkinter.Entry(self.top) # 生成文本框組件
self.entry.pack()
self.entry.focus() # 文本框獲得焦點
button = tkinter.Button(self.top, text='Ok', command=self.Ok) #生成按鈕,設置按鈕處理函數
button.pack()
def Ok(self): # 定義按鈕事件處理函數
self.input = self.entry.get() # 獲取文本框中的內容,保存爲input
self.top.destroy() #銷燬對話框
def get(self): # 返回在文本框中內容
return self.input
class MyButton(object):
def __init__(self, root, type):
self.root = root # 保持父窗口引用
if type == 0: # 類不同創建不同按鈕
self.button = tkinter.Button(root, text='Create', command=self.Create)
else:
self.button = tkinter.Button(root, text='Quit', command=self.Quit)
self.button.pack()
def Create(self):
d = MyDialog(self.root) # 生成一個對話框
self.button.wait_window(d.top) # 等待對話框結束
tkinter.messagebox.showinfo('Python', 'You input:\n' + d.get()) # 輸出輸入值,重點語句
def Quit(self): # 退出主窗口
self.root.quit()
root = tkinter.Tk()
MyButton(root, 0)
MyButton(root, 1)
root.mainloop()