版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zhuisaozhang1292/article/details/85724742
范例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