tkinter中對話框有顏色選擇對話框、文件對話框、輸入數據對話框和消息對話框等。在這個小案例裏使用了顏色對話框,獲得顏色修改Label的背景色,使用了文件對話框打開文本文檔,顯示在Label中,運用數據對話框輸入一個整型數顯示在Label中。
案例代碼如下:
from tkinter import *
from tkinter.colorchooser import *
from tkinter.filedialog import *
from tkinter.simpledialog import *
class Application(Frame):
def __init__(self,master = None):
super().__init__(master)
self.master = master
self.pack()
self.createWidget()
def createWidget(self):
self.btn1 = Button(self.master,text='choose the color')
self.btn1.place(relx = 0.4,rely = 0.1,relwidth = 0.18,relheight= 0.1)
self.btn1.bind("<Button-1>",self.test1)
self.btn2 = Button(self.master,text='choose the file')
self.btn2.place(relx = 0.2,rely = 0.1,relwidth = 0.15,relheight= 0.1)
self.btn2.bind("<Button-1>",self.testOpen)
self.show = Label(self.master,width = 100,height = 20,bg ="white")
self.show.place(relx = 0.2,rely = 0.3,relwidth = 0.6,relheight = 0.5)
self.btn3 = Button(self.master,text='ask for Interger')
self.btn3.place(relx = 0.6,rely = 0.1,relwidth = 0.2,relheight= 0.1)
self.btn3.bind("<Button-1>",self.testAskInt)
def test1(self,event):
#打開一個顏色選擇對話框
acol = askcolor(color='blue',title='color choose tools')
print(acol)
self.show["bg"] = acol[1]
def testOpen(self,event):
#打開一個文件選擇對話框
with askopenfile(title = "up file",initialdir="d:",filetypes=[("textFile",".txt")]) as f:
self.show["text"] = f.read()
def testAskInt(self,event):
#打開一個請求輸入整型數據對話框。
num = askinteger(title = "input age",prompt = "Please input a number for age",initialvalue = 18,minvalue = 1,maxvalue = 130)
self.show["text"] = num
if __name__ == "__main__":
root = Tk()
root.geometry("630x300+200+300")
app = Application(master = root)
root.mainloop()
運行效果截圖如下: