python GUI程式設計範例
阿新 • • 發佈:2019-01-10
範例1:
#coding:utf-8 #GUI介面程式設計 from tkinter import * #控制元件基礎包,匯入這個包後,這個包下的所有函式可以直接呼叫 import tkinter from tkinter import Label, Button, END from tkinter.tix import Tk, Control, ComboBox #升級的組合控制元件包 from tkinter.messagebox import showinfo, showwarning, showerror #各種型別的提示框 #除此之外還有很多介面程式設計的包 #頂層視窗 top = tkinter.Tk() #建立頂層視窗 top.geometry('250x150') #初始化視窗大小 top.title("標題") top.tk.eval('package require Tix') #引入升級包,這樣才能使用升級的組合控制元件 #標籤控制元件 label = tkinter.Label(top, text='Hello World!',font='Helvetica -12 bold') #建立標籤 label.pack(fill=Y, expand=1) #填充到介面 #按鈕控制元件 button = tkinter.Button(top, text='QUIT',command=top.quit,activeforeground='white',activebackground='red', bg='red', fg='white') #建立按鈕,command為回撥函式 button.pack(fill=tkinter.X, expand=1) #fill=tkinter.X表示橫向拉伸完全 #自定義函式,控制控制元件的縮放 def resize(ev=None): label.config(font='Helvetica -%d bold' % scale.get()) #比例尺控制元件 scale = Scale(top, from_=10, to=40,orient=HORIZONTAL, command=resize) #縮放比例尺 scale.set(12) #初始值 scale.pack(fill=X, expand=1) #填充到介面 #NumericUpDown控制元件 ct = Control(top, label='Number:',integer=True, max=12, min=2, value=2, step=2) ct.label.config(font='Helvetica -14 bold') ct.pack() #ComboBox控制元件 cb = ComboBox(top, label='Type:', editable=True) for animal in ('dog', 'cat', 'hamster', 'python'): cb.insert(END, animal) cb.pack() tkinter.mainloop() #執行這個GUI應用
範例2:
''' Created on 2019年1月3日 @author: hcl ''' import tkinter from tkinter import Button, Canvas, Entry, Frame, filedialog,messagebox from tkinter.tix import Control from PIL import Image, ImageTk import os class DataAnnotationWindow(object): def __init__(self): self.img_Wid = 500 self.img_Hei = 500 self.win_wid = self.img_Wid + 200 self.win_Hei = self.img_Hei # init state control variable self.has_select_path = False # sign has select image path(to do data annotation) or not self.img_path = '' self.img_list = [] # create main window self.mainWin = tkinter.Tk() self.mainWin.geometry(str(self.win_wid) + 'x' + str(self.win_Hei)) # init the size of window self.mainWin.title("data annotation tool") self.mainWin.tk.eval('package require Tix') # create init image(a black background) self.img = Image.new("RGB", (self.img_Wid, self.img_Hei), (0,0,0)) self.photo_img = ImageTk.PhotoImage(self.img) # create Canvas control self.cv = Canvas(self.mainWin, bg = 'white', width = self.img_Wid, height = self.img_Hei) self.cv.create_image((0,0), anchor=tkinter.NW, image=self.photo_img) self.cv.pack(side=tkinter.LEFT, expand=True) # create total Frame to lay out all components self.frame = Frame(self.mainWin) self.frame.pack(fill=tkinter.X, expand=tkinter.YES, side=tkinter.LEFT) # create text control root_save_path = './data_annotation_result' self.entry= Entry(self.frame, state = 'normal') self.entry.pack(side = tkinter.TOP, fill = tkinter.X) self.entry.insert(0, root_save_path) # mkdir of annotation result self.categoryList = ['Dog', 'Cat'] self.category_savepath_list = [] for category in self.categoryList: cur_category_save_path = os.path.join(root_save_path, category) self.category_savepath_list.append(cur_category_save_path) if os.path.exists(cur_category_save_path) == False: os.mkdir(cur_category_save_path) # create 'START' button self.btn_start = Button(self.frame, text='START', command=self._selectPath, activeforeground='blue', activebackground='white', bg='blue', fg='white') self.btn_start.pack(side = tkinter.TOP, pady=30) # create data annotation label button self.btn_dog = Button(self.frame, text='Dog',command=lambda:self._labelButtonClick('Dog'), activeforeground='black', activebackground='blue', bg='white', fg='black') self.btn_dog.pack(side = tkinter.TOP, pady=10) # create data annotation label button self.btn_cat = Button(self.frame, text='Cat',command=lambda:self._labelButtonClick('Cat'), activeforeground='black', activebackground='blue', bg='white', fg='black') self.btn_cat.pack(side = tkinter.TOP, pady=10) #NumericUpDown控制元件 self.num_count = Control(self.frame,integer=True, max=-1, min=-1, value=-1, step=1, label='current Image:', command=self._showImage) self.num_count.label.config(font='Helvetica -14 bold') self.num_count.pack(side = tkinter.TOP, pady=50) # create 'QUIT' button self.btn_quit = Button(self.frame, text='QUIT',command=self.mainWin.quit,activeforeground='blue', activebackground='white', bg='red', fg='white') self.btn_quit.pack(side = tkinter.BOTTOM, pady=10) def _showImage(self, ev=None): if self.has_select_path: if int(self.num_count['value']) == -1: # create init image(a black background) self.img = Image.new("RGB", (self.img_Wid, self.img_Hei), (0,0,0)) self.photo_img = ImageTk.PhotoImage(self.img) self.cv.create_image((0,0), anchor=tkinter.NW, image=self.photo_img) return else: img_cur_path = self.img_list[int(self.num_count['value'])] self.img = Image.open(img_cur_path).resize((self.img_Wid, self.img_Hei)) self.photo_img = ImageTk.PhotoImage(self.img) self.cv.create_image((0,0), anchor=tkinter.NW, image=self.photo_img) def _labelButtonClick(self, label): cur_idx = int(self.num_count['value']) if cur_idx != -1: # save cur image's annotation result catgory_idx = self.categoryList.index(label) save_path = self.category_savepath_list[catgory_idx] cur_img_name = self.img_list[cur_idx].split('\\')[-1] save_path = os.path.join(save_path, cur_img_name) self.img.save(save_path) # check has next image or not if cur_idx + 1 < len(self.img_list): self.num_count['value'] = str(cur_idx + 1) else: messagebox.showinfo(title='thanks', message='all the data annotation mission has finished~') def _selectPath(self): self.img_path = filedialog.askdirectory() self.img_list = self._getImagList() if len(self.img_list) > 0: self.has_select_path = True self.num_count.config(max = len(self.img_list)) self.num_count['value'] = str(0) else: self.has_select_path = False self.num_count['value'] = str(-1) self.num_count.config(max = -1) messagebox.showwarning('warning','No available images detected! please re-select image path and start') def _getImagList(self): img_list = [] img_suffix = ['jpg', 'png', 'jpeg', 'bmp'] for root, dirs, files in os.walk(self.img_path): for file_name in files: suffix = file_name.split('.')[-1] if suffix in img_suffix: cur_img_path = os.path.join(root, file_name) img_list.append(cur_img_path) return img_list if __name__ == '__main__': data_annotation_tool = DataAnnotationWindow() tkinter.mainloop() # run GUI