tkinter

tkinter

简介:简单的GUI编程,python自带的包

参考链接1:https://github.com/MorvanZhou/tutorials/tree/master/tkinterTUT

参考链接2:http://www.bczl.xyz/tkinter/doc/1%20%E6%A6%82%E8%BF%B0.html

 

1 label_button

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x100')

var = tk.StringVar()
l = tk.Label(window, textvariable=var, bg='green', font=('Arial', 12), width=15,
             height=2)
#l = tk.Label(window, text='OMG! this is TK!', bg='green', font=('Arial', 12), width=15, height=2)
l.pack()

on_hit = False
def hit_me():
    global on_hit
    if on_hit == False:
        on_hit = True
        var.set('you hit me')
    else:
        on_hit = False
        var.set('')

b = tk.Button(window, text='hit me', width=15,
              height=2, command=hit_me)
b.pack()


window.mainloop()
View Code

 

2 entry_text

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')
# e = tk.Entry(window, show="*")
e = tk.Entry(window, show="1")
e.pack()

def insert_point():
    var = e.get()
    t.insert('insert', var)
def insert_end():
    var = e.get()
    # t.insert('end', var)
    t.insert(2.2, var)

b1 = tk.Button(window, text='insert point', width=15,
              height=2, command=insert_point)
b1.pack()
b2 = tk.Button(window, text='insert end',
               command=insert_end)
b2.pack()
t = tk.Text(window, height=2)
t.pack()

window.mainloop()
View Code

 

3 listbox

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

var1 = tk.StringVar()
l = tk.Label(window, bg='yellow', width=4, textvariable=var1)
l.pack()

def print_selection():
    value = lb.get(lb.curselection())
    var1.set(value)

b1 = tk.Button(window, text='print selection', width=15,
              height=2, command=print_selection)
b1.pack()

var2 = tk.StringVar()
var2.set((11,22,33,44))
lb = tk.Listbox(window, listvariable=var2)
list_items = [1,2,3,4]
for item in list_items:
    lb.insert('end', item)
lb.insert(1, 'first')
lb.insert(2, 'second')
lb.delete(2)
lb.pack()

window.mainloop()
View Code

 

4 radiobutton

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

var = tk.StringVar()
l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()

def print_selection():
    l.config(text='you have selected ' + var.get())

r1 = tk.Radiobutton(window, text='Option A',
                    variable=var, value='A',
                    command=print_selection)
r1.pack()
r2 = tk.Radiobutton(window, text='Option B',
                    variable=var, value='B',
                    command=print_selection)
r2.pack()
r3 = tk.Radiobutton(window, text='Option C',
                    variable=var, value='C',
                    command=print_selection)
r3.pack()


window.mainloop()
View Code

 

5 scale

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()

def print_selection(v):
    l.config(text='you have selected ' + v)

s = tk.Scale(window, label='try me', from_=5, to=11, orient=tk.HORIZONTAL,
             length=200, showvalue=0, tickinterval=2, resolution=0.01, command=print_selection)
s.pack()

window.mainloop()
View Code

 

6 checkbutton

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

l = tk.Label(window, bg='yellow', width=20, text='empty')
l.pack()

def print_selection():
    if (var1.get() == 1) & (var2.get() == 0):
        l.config(text='I love only Python ')
    elif (var1.get() == 0) & (var2.get() == 1):
        l.config(text='I love only C++')
    elif (var1.get() == 0) & (var2.get() == 0):
        l.config(text='I do not love either')
    else:
        l.config(text='I love both')

var1 = tk.IntVar()
var2 = tk.IntVar()
c1 = tk.Checkbutton(window, text='Python', variable=var1, onvalue=1, offvalue=0,
                    command=print_selection)
c2 = tk.Checkbutton(window, text='C++', variable=var2, onvalue=1, offvalue=0,
                    command=print_selection)
c1.pack()
c2.pack()


window.mainloop()
View Code

 

7canvas

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

canvas = tk.Canvas(window, bg='blue', height=100, width=200)
image_file = tk.PhotoImage(file='ins.gif')
image = canvas.create_image(10, 10, anchor='nw', image=image_file)
x0, y0, x1, y1= 50, 50, 80, 80
line = canvas.create_line(x0, y0, x1, y1)
oval = canvas.create_oval(x0, y0, x1, y1, fill='red')
arc = canvas.create_arc(x0+30, y0+30, x1+30, y1+30, start=0, extent=180)
rect = canvas.create_rectangle(100, 30, 100+20, 30+20)
canvas.pack()

def moveit():
    canvas.move(rect, 0, 2)

b = tk.Button(window, text='move', command=moveit).pack()


window.mainloop()
View Code

 

8 menubar

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

l = tk.Label(window, text='', bg='yellow')
l.pack()
counter = 0
def do_job():
    global counter
    l.config(text='do '+ str(counter))
    counter+=1

menubar = tk.Menu(window)
filemenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='File', menu=filemenu)
filemenu.add_command(label='New', command=do_job)
filemenu.add_command(label='Open', command=do_job)
filemenu.add_command(label='Save', command=do_job)
filemenu.add_separator()
filemenu.add_command(label='Exit', command=window.quit)

editmenu = tk.Menu(menubar, tearoff=0)
menubar.add_cascade(label='Edit', menu=editmenu)
editmenu.add_command(label='Cut', command=do_job)
editmenu.add_command(label='Copy', command=do_job)
editmenu.add_command(label='Paste', command=do_job)

submenu = tk.Menu(filemenu)
filemenu.add_cascade(label='Import', menu=submenu, underline=0)
submenu.add_command(label="Submenu1", command=do_job)

window.config(menu=menubar)

window.mainloop()
View Code

 

9 frame

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.title('my window')
window.geometry('200x200')
tk.Label(window, text='on the window').pack()

frm = tk.Frame(window)
frm.pack()
frm_l = tk.Frame(frm, )
frm_r = tk.Frame(frm)
frm_l.pack(side='left')
frm_r.pack(side='right')

tk.Label(frm_l, text='on the frm_l1').pack()
tk.Label(frm_l, text='on the frm_l2').pack()
tk.Label(frm_r, text='on the frm_r1').pack()
window.mainloop()
View Code

 

10 msgbox

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk
import tkinter.messagebox

window = tk.Tk()
window.title('my window')
window.geometry('200x200')

def hit_me():
    #tk.messagebox.showinfo(title='Hi', message='hahahaha')   # return 'ok'
    #tk.messagebox.showwarning(title='Hi', message='nononono')   # return 'ok'
    #tk.messagebox.showerror(title='Hi', message='No!! never')   # return 'ok'
    #print(tk.messagebox.askquestion(title='Hi', message='hahahaha'))   # return 'yes' , 'no'
    #print(tk.messagebox.askyesno(title='Hi', message='hahahaha'))   # return True, False
    print(tk.messagebox.asktrycancel(title='Hi', message='hahahaha'))   # return True, False
    print(tk.messagebox.askokcancel(title='Hi', message='hahahaha'))   # return True, False
    print(tk.messagebox.askyesnocancel(title="Hi", message="haha"))     # return, True, False, None

tk.Button(window, text='hit me', command=hit_me).pack()
window.mainloop()
View Code

 

11 position

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk

window = tk.Tk()
window.geometry('200x200')

#canvas = tk.Canvas(window, height=150, width=500)
#canvas.grid(row=1, column=1)
#image_file = tk.PhotoImage(file='welcome.gif')
#image = canvas.create_image(0, 0, anchor='nw', image=image_file)

#tk.Label(window, text='1').pack(side='top')
#tk.Label(window, text='1').pack(side='bottom')
#tk.Label(window, text='1').pack(side='left')
#tk.Label(window, text='1').pack(side='right')

#for i in range(4):
    #for j in range(3):
        #tk.Label(window, text=1).grid(row=i, column=j, padx=10, pady=10)

tk.Label(window, text=1).place(x=20, y=10, anchor='nw')

window.mainloop()
View Code

 

 

实战案例:

1 登录-注册

# View more python learning tutorial on my Youtube and Youku channel!!!

# Youtube video tutorial: https://www.youtube.com/channel/UCdyjiB5H8Pu7aDTNVXTTpcg
# Youku video tutorial: http://i.youku.com/pythontutorial

import tkinter as tk
from tkinter import messagebox  # import this to fix messagebox error
import pickle

window = tk.Tk()
window.title('Welcome to Mofan Python')
window.geometry('450x300')

# welcome image
canvas = tk.Canvas(window, height=200, width=500)
image_file = tk.PhotoImage(file='welcome.gif')
image = canvas.create_image(0,0, anchor='nw', image=image_file)
canvas.pack(side='top')

# user information
tk.Label(window, text='User name: ').place(x=50, y= 150)
tk.Label(window, text='Password: ').place(x=50, y= 190)

var_usr_name = tk.StringVar()
var_usr_name.set('example@python.com')
entry_usr_name = tk.Entry(window, textvariable=var_usr_name)
entry_usr_name.place(x=160, y=150)
var_usr_pwd = tk.StringVar()
entry_usr_pwd = tk.Entry(window, textvariable=var_usr_pwd, show='*')
entry_usr_pwd.place(x=160, y=190)

def usr_login():
    usr_name = var_usr_name.get()
    usr_pwd = var_usr_pwd.get()
    try:
        with open('usrs_info.pickle', 'rb') as usr_file:
            usrs_info = pickle.load(usr_file)
    except FileNotFoundError:
        with open('usrs_info.pickle', 'wb') as usr_file:
            usrs_info = {'admin': 'admin'}
            pickle.dump(usrs_info, usr_file)
    if usr_name in usrs_info:
        if usr_pwd == usrs_info[usr_name]:
            tk.messagebox.showinfo(title='Welcome', message='How are you? ' + usr_name)
        else:
            tk.messagebox.showerror(message='Error, your password is wrong, try again.')
    else:
        is_sign_up = tk.messagebox.askyesno('Welcome',
                               'You have not signed up yet. Sign up today?')
        if is_sign_up:
            usr_sign_up()

def usr_sign_up():
    def sign_to_Mofan_Python():
        np = new_pwd.get()
        npf = new_pwd_confirm.get()
        nn = new_name.get()
        with open('usrs_info.pickle', 'rb') as usr_file:
            exist_usr_info = pickle.load(usr_file)
        if np != npf:
            tk.messagebox.showerror('Error', 'Password and confirm password must be the same!')
        elif nn in exist_usr_info:
            tk.messagebox.showerror('Error', 'The user has already signed up!')
        else:
            exist_usr_info[nn] = np
            with open('usrs_info.pickle', 'wb') as usr_file:
                pickle.dump(exist_usr_info, usr_file)
            tk.messagebox.showinfo('Welcome', 'You have successfully signed up!')
            window_sign_up.destroy()
    window_sign_up = tk.Toplevel(window)
    window_sign_up.geometry('350x200')
    window_sign_up.title('Sign up window')

    new_name = tk.StringVar()
    new_name.set('example@python.com')
    tk.Label(window_sign_up, text='User name: ').place(x=10, y= 10)
    entry_new_name = tk.Entry(window_sign_up, textvariable=new_name)
    entry_new_name.place(x=150, y=10)

    new_pwd = tk.StringVar()
    tk.Label(window_sign_up, text='Password: ').place(x=10, y=50)
    entry_usr_pwd = tk.Entry(window_sign_up, textvariable=new_pwd, show='*')
    entry_usr_pwd.place(x=150, y=50)

    new_pwd_confirm = tk.StringVar()
    tk.Label(window_sign_up, text='Confirm password: ').place(x=10, y= 90)
    entry_usr_pwd_confirm = tk.Entry(window_sign_up, textvariable=new_pwd_confirm, show='*')
    entry_usr_pwd_confirm.place(x=150, y=90)

    btn_comfirm_sign_up = tk.Button(window_sign_up, text='Sign up', command=sign_to_Mofan_Python)
    btn_comfirm_sign_up.place(x=150, y=130)

# login and sign up button
btn_login = tk.Button(window, text='Login', command=usr_login)
btn_login.place(x=170, y=230)
btn_sign_up = tk.Button(window, text='Sign up', command=usr_sign_up)
btn_sign_up.place(x=270, y=230)

window.mainloop()
View Code

 

2 自制文本编辑器

 

from editor_style import theme_color, ICONS
from tkinter import *
from tkinter import filedialog, messagebox
from tkinter.ttk import Scrollbar, Checkbutton, Label, Button
import os


class EditorPlus(Tk):
    icon_res = []
    file_name = None

    def __init__(self):
        super().__init__()
        self._set_window_()
        self._create_menu_bar_()
        self._create_shortcut_bar_()
        self._create_body_()
        self._create_right_popup_menu()

    # 设置初始窗口的属性
    def _set_window_(self):
        self.title("EditorPlus")
        scn_width, scn_height = self.maxsize()
        wm_val = '750x450+%d+%d' % ((scn_width - 750) / 2, (scn_height - 450) / 2)
        self.geometry(wm_val)
        self.iconbitmap("img/editor.ico")
        self.protocol('WM_DELETE_WINDOW', self.exit_editor)

    # 创建整个菜单栏
    def _create_menu_bar_(self):
        menu_bar = Menu(self)
        # 创建文件的联级菜单
        file_menu = Menu(menu_bar, tearoff=0)
        file_menu.add_command(label='新建', accelerator='Ctrl+N', command=self.new_file)
        file_menu.add_command(label='打开', accelerator='Ctrl+O', command=self.open_file)
        file_menu.add_command(label='保存', accelerator='Ctrl+S', command=self.save)
        file_menu.add_command(label='另存为', accelerator='Shift+Ctrl+S', command=self.save_as)
        file_menu.add_separator()
        file_menu.add_command(label='退出', accelerator='Alt+F4', command=self.exit_editor)

        # 在菜单栏上添加菜单标签,并将该标签与相应的联级菜单关联起来
        menu_bar.add_cascade(label='文件', menu=file_menu)

        # 创建编辑的联级菜单
        edit_menu = Menu(menu_bar, tearoff=0)
        edit_menu.add_command(label='撤销', accelerator='Ctrl+Z', command=lambda: self.handle_menu_action('撤销'))
        edit_menu.add_command(label='恢复', accelerator='Ctrl+Y', command=lambda: self.handle_menu_action('恢复'))
        edit_menu.add_separator()
        edit_menu.add_command(label='剪切', accelerator='Ctrl+X', command=lambda: self.handle_menu_action('剪切'))
        edit_menu.add_command(label='复制', accelerator='Ctrl+C', command=lambda: self.handle_menu_action('复制'))
        edit_menu.add_command(label='粘贴', accelerator='Ctrl+V', command=lambda: self.handle_menu_action('粘贴'))
        edit_menu.add_separator()
        edit_menu.add_command(label='查找', accelerator='Ctrl+F', command=self.find_text)
        edit_menu.add_separator()
        edit_menu.add_command(label='全选', accelerator='Ctrl+A', command=self.select_all)
        menu_bar.add_cascade(label='编辑', menu=edit_menu)

        # 视图菜单
        view_menu = Menu(menu_bar, tearoff=0)
        self.is_show_line_num = IntVar()
        self.is_show_line_num.set(1)
        view_menu.add_checkbutton(label='显示行号', variable=self.is_show_line_num,
                                  command=self._update_line_num)

        self.is_highlight_line = IntVar()
        view_menu.add_checkbutton(label='高亮当前行', onvalue=1, offvalue=0,
                                  variable=self.is_highlight_line, command=self._toggle_highlight)

        # 在主题菜单中再添加一个子菜单列表
        themes_menu = Menu(menu_bar, tearoff=0)
        view_menu.add_cascade(label='主题', menu=themes_menu)

        self.theme_choice = StringVar()
        self.theme_choice.set('Default')
        for k in sorted(theme_color):
            themes_menu.add_radiobutton(label=k, variable=self.theme_choice,
                                        command=self.change_theme)

        menu_bar.add_cascade(label='视图', menu=view_menu)

        about_menu = Menu(menu_bar, tearoff=0)
        about_menu.add_command(label='关于', command=lambda: self.show_messagebox('关于'))
        about_menu.add_command(label='帮助', command=lambda: self.show_messagebox('帮助'))
        menu_bar.add_cascade(label='关于', menu=about_menu)
        self["menu"] = menu_bar

    # 创建快捷菜单栏
    def _create_shortcut_bar_(self):
        shortcut_bar = Frame(self, height=25, background='#20b2aa')
        shortcut_bar.pack(fill='x')

        for i, icon in enumerate(ICONS):
            tool_icon = PhotoImage(file='img/%s.gif' % (icon,))
            tool_btn = Button(shortcut_bar, image=tool_icon,
                              command=self._shortcut_action(icon))

            tool_btn.pack(side='left')
            self.icon_res.append(tool_icon)

    # 创建程序主体
    def _create_body_(self):
        # 创建行号栏 (takefocus=0 屏蔽焦点)
        self.line_number_bar = Text(self, width=4, padx=3, takefocus=0, border=0,
                                    background='#F0E68C', state='disabled')
        self.line_number_bar.pack(side='left', fill='y')
        # 创建文本输入框(undo是否启用撤销机制)
        self.content_text = Text(self, wrap='word', undo=True)
        self.content_text.pack(expand='yes', fill='both')
        self.content_text.bind('<Control-N>', self.new_file)
        self.content_text.bind('<Control-n>', self.new_file)
        self.content_text.bind('<Control-O>', self.open_file)
        self.content_text.bind('<Control-o>', self.open_file)
        self.content_text.bind('<Control-S>', self.save)
        self.content_text.bind('<Control-s>', self.save)
        self.content_text.bind('<Control-A>', self.select_all)
        self.content_text.bind('<Control-a>', self.select_all)
        self.content_text.bind('<Control-f>', self.find_text)
        self.content_text.bind('<Control-F>', self.find_text)
        self.content_text.bind('<Any-KeyPress>', lambda e: self._update_line_num())
        self.bind_all('<KeyPress-F1>', lambda e: self.show_messagebox("帮助"))
        self.content_text.tag_configure('active_line', background='#EEEEE0')

        # 创建滚动条
        scroll_bar = Scrollbar(self.content_text)
        scroll_bar["command"] = self.content_text.yview
        self.content_text["yscrollcommand"] = scroll_bar.set
        scroll_bar.pack(side='right', fill='y')

    # 鼠标右键弹出菜单
    def _create_right_popup_menu(self):
        popup_menu = Menu(self.content_text, tearoff=0)
        for it1, it2 in zip(['剪切', '复制', '粘贴', '撤销', '恢复'],
                            ['cut', 'copy', 'paste', 'undo', 'redo']):
            popup_menu.add_command(label=it1, compound='left',
                                   command=self._shortcut_action(it2))
        popup_menu.add_separator()
        popup_menu.add_command(label='全选', command=self.select_all)
        self.content_text.bind('<Button-3>',
                               lambda event: popup_menu.tk_popup(event.x_root, event.y_root))

    def _update_line_num(self):
        if self.is_show_line_num.get():
            row, col = self.content_text.index("end").split('.')
            line_num_content = "\n".join([str(i) for i in range(1, int(row))])
            self.line_number_bar.config(state='normal')
            self.line_number_bar.delete('1.0', 'end')
            self.line_number_bar.insert('1.0', line_num_content)
            self.line_number_bar.config(state='disabled')
        else:
            self.line_number_bar.config(state='normal')
            self.line_number_bar.delete('1.0', 'end')
            self.line_number_bar.config(state='disabled')

    def _toggle_highlight(self):
        if self.is_highlight_line.get():
            self.content_text.tag_remove("active_line", 1.0, "end")
            self.content_text.tag_add("active_line", "insert linestart", "insert lineend+1c")
            self.content_text.after(200, self._toggle_highlight)
        else:
            self.content_text.tag_remove("active_line", 1.0, "end")

    def change_theme(self):
        selected_theme = self.theme_choice.get()
        fg_bg = theme_color.get(selected_theme)
        fg_color, bg_color = fg_bg.split('.')
        self.content_text.config(bg=bg_color, fg=fg_color)

    # 处理菜单响应,返回break,使事件不在传递
    def handle_menu_action(self, action_type):
        if action_type == "撤销":
            self.content_text.event_generate("<<Undo>>")
        elif action_type == "恢复":
            self.content_text.event_generate("<<Redo>>")
        elif action_type == "剪切":
            self.content_text.event_generate("<<Cut>>")
        elif action_type == "复制":
            self.content_text.event_generate("<<Copy>>")
        elif action_type == "粘贴":
            self.content_text.event_generate("<<Paste>>")

        if action_type != "复制":
            self._update_line_num()

        return "break"

    def show_messagebox(self, type):
        if type == "帮助":
            messagebox.showinfo("帮助", "这是帮助文档!", icon='question')
        else:
            messagebox.showinfo("关于", "EditorPlus_V0.1")

    # 响应快捷菜单
    def _shortcut_action(self, type):
        def handle():
            if type == "new_file":
                self.new_file()
            elif type == "open_file":
                self.open_file()
            elif type == "save":
                self.save()
            elif type == "cut":
                self.handle_menu_action("剪切")
            elif type == "copy":
                self.handle_menu_action("复制")
            elif type == "paste":
                self.handle_menu_action("粘贴")
            elif type == "undo":
                self.handle_menu_action("撤销")
            elif type == "redo":
                self.handle_menu_action("恢复")
            elif type == "find_text":
                self.find_text()

            if type != "copy" and type != "save":
                self._update_line_num()

        return handle

    def select_all(self, event=None):
        self.content_text.tag_add('sel', '1.0', 'end')
        return "break"

    def new_file(self, event=None):
        self.title("New - EditorPlus")
        self.content_text.delete(1.0, END)
        self.file_name = None

    def open_file(self, event=None):
        input_file = filedialog.askopenfilename(
            filetypes=[("所有文件", "*.*"), ("文本文档", "*.txt")])
        if input_file:
            self.title("%s - EditorPlus" % os.path.basename(input_file))
            self.file_name = input_file
            self.content_text.delete(1.0, END)
            with open(input_file, 'r') as _file:
                self.content_text.insert(1.0, _file.read())

    def save(self, event=None):
        if not self.file_name:
            self.save_as()
        else:
            self._write_to_file(self.file_name)

    def save_as(self, event=None):
        input_file = filedialog.asksaveasfilename(
            filetypes=[("All Files", "*.*"), ("文本文档", "*.txt")])
        if input_file:
            self.file_name = input_file
            self._write_to_file(self.file_name)

    def _write_to_file(self, file_name):
        try:
            content = self.content_text.get(1.0, 'end')
            with open(file_name, 'w') as the_file:
                the_file.write(content)
            self.title("%s - EditorPlus" % os.path.basename(file_name))
        except IOError:
            messagebox.showwarning("保存", "保存失败!")

    # 查找对话框
    def find_text(self, event=None):
        search_toplevel = Toplevel(self)
        search_toplevel.title('查找文本')
        search_toplevel.transient(self)  # 总是让搜索框显示在其父窗体之上
        search_toplevel.resizable(False, False)
        Label(search_toplevel, text="查找全部:").grid(row=0, column=0, sticky='e')
        search_entry_widget = Entry(search_toplevel, width=25)
        search_entry_widget.grid(row=0, column=1, padx=2, pady=2, sticky='we')
        search_entry_widget.focus_set()
        ignore_case_value = IntVar()
        Checkbutton(search_toplevel, text='忽略大小写', variable=ignore_case_value).grid(
            row=1, column=1, sticky='e', padx=2, pady=2)

        Button(search_toplevel, text="查找", command=lambda: self.search_result(
            search_entry_widget.get(), ignore_case_value.get(), search_toplevel, search_entry_widget)
               ).grid(row=0, column=2, sticky='e' + 'w', padx=2, pady=2)

        def close_search_window():
            self.content_text.tag_remove('match', '1.0', "end")
            search_toplevel.destroy()

        search_toplevel.protocol('WM_DELETE_WINDOW', close_search_window)
        return "break"

    def search_result(self, key, ignore_case, search_toplevel, search_box):
        self.content_text.tag_remove('match', '1.0', "end")
        matches_found = 0
        if key:
            start_pos = '1.0'
            while True:
                # search返回第一个匹配上的结果的开始索引,返回空则没有匹配的(nocase:忽略大小写)
                start_pos = self.content_text.search(key, start_pos, nocase=ignore_case, stopindex="end")
                if not start_pos:
                    break
                end_pos = '{}+{}c'.format(start_pos, len(key))
                self.content_text.tag_add('match', start_pos, end_pos)
                matches_found += 1
                start_pos = end_pos
            self.content_text.tag_config('match', foreground='red', background='yellow')
        search_box.focus_set()
        search_toplevel.title('发现%d个匹配的' % matches_found)

    def exit_editor(self):
        if messagebox.askokcancel("退出?", "确定退出吗?"):
            self.destroy()


if "__main__" == __name__:
    app = EditorPlus()
    app.mainloop()
editor.pyw
ICONS = ['new_file', 'open_file', 'save', 'cut', 'copy', 'paste',
         'undo', 'redo', 'find_text']


theme_color = {
    'Default': '#000000.#FFFFFF',
    'Greygarious': '#83406A.#D1D4D1',
    'Aquamarine': '#5B8340.#D1E7E0',
    'Bold Beige': '#4B4620.#FFF0E1',
    'Cobalt Blue': '#ffffBB.#3333aa',
    'Olive Green': '#D1E7E0.#5B8340',
    'Night Mode': '#FFFFFF.#000000',
}
editor_style.py

 

3 表白

'''配置文件'''
import os


# 窗口大小(width, height)
SCREENSIZE = (500, 260)
# 定义一些颜色
RED = (255, 0, 0)
BLACK = (0, 0, 0)
AZURE = (240, 255, 255)
WHITE = (255, 255, 255)
MISTYROSE = (255, 228, 225)
PALETURQUOISE = (175, 238, 238)
PAPAYAWHIP = (255, 239, 213)
LIGHTGRAY = (211, 211, 211)
GAINSBORO = (230, 230, 230)
WHITESMOKE = (245, 245, 245)
DARKGRAY = (169, 169, 169)
BLUE = (0, 0, 255)
DEEPSKYBLUE = (0, 191, 255)
SKYBLUE = (135, 206, 235)
LIGHTSKYBLUE = (135, 206, 250)
# 背景音乐路径
BGM_PATH = os.path.join(os.getcwd(), 'resources/music/bgm.mp3')
# 字体路径
FONT_PATH = os.path.join(os.getcwd(), 'resources/font/STXINGKA.TTF')
# 背景图片路径
BG_IMAGE_PATH = os.path.join(os.getcwd(), 'resources/images/bg.png')
# ICON路径
ICON_IMAGE_PATH = os.path.join(os.getcwd(), 'resources/images/icon.png')
cfg.py
import sys
import cfg
import random
import pygame
from tkinter import Tk, messagebox

'''
Function:
    按钮类
Initial Args:
    --x, y: 按钮左上角坐标
    --width, height: 按钮宽高
    --text: 按钮显示的文字
    --fontpath: 字体路径
    --fontsize: 字体大小
    --fontcolor: 字体颜色
    --bgcolors: 按钮背景颜色
    --is_want_to_be_selected: 按钮是否想被玩家选中
    --screensize: 软件屏幕大小
'''
class Button(pygame.sprite.Sprite):
    def __init__(self, x, y, width, height, text, fontpath, fontsize, fontcolor, bgcolors, edgecolor, edgesize=1, is_want_to_be_selected=True, screensize=None, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.font = pygame.font.Font(fontpath, fontsize)
        self.fontcolor = fontcolor
        self.bgcolors = bgcolors
        self.edgecolor = edgecolor
        self.edgesize = edgesize
        self.is_want_tobe_selected = is_want_to_be_selected
        self.screensize = screensize
    '''自动根据各种情况将按钮绑定到屏幕'''
    def draw(self, screen, mouse_pos):
        # 鼠标在按钮范围内
        if self.rect.collidepoint(mouse_pos):
            # --不想被选中
            if not self.is_want_tobe_selected:
                while self.rect.collidepoint(mouse_pos):
                    self.rect.left, self.rect.top = random.randint(0, self.screensize[0]-self.rect.width), random.randint(0, self.screensize[1]-self.rect.height)
            pygame.draw.rect(screen, self.bgcolors[0], self.rect, 0)
            pygame.draw.rect(screen, self.edgecolor, self.rect, self.edgesize)
        # 鼠标不在按钮范围内
        else:
            pygame.draw.rect(screen, self.bgcolors[1], self.rect, 0)
            pygame.draw.rect(screen, self.edgecolor, self.rect, self.edgesize)
        text_render = self.font.render(self.text, True, self.fontcolor)
        fontsize = self.font.size(self.text)
        screen.blit(text_render, (self.rect.x+(self.rect.width-fontsize[0])/2, self.rect.y+(self.rect.height-fontsize[1])/2))


'''在指定位置显示文字'''
def showText(screen, text, position, fontpath, fontsize, fontcolor, is_bold=False):
    font = pygame.font.Font(fontpath, fontsize)
    font.set_bold(is_bold)
    text_render = font.render(text, True, fontcolor)
    screen.blit(text_render, position)


'''主函数'''
def main():
    # 初始化
    pygame.init()
    screen = pygame.display.set_mode(cfg.SCREENSIZE, 0, 32)
    pygame.display.set_icon(pygame.image.load(cfg.ICON_IMAGE_PATH))
    pygame.display.set_caption('来自一位喜欢你的小哥哥')
    # 背景音乐
    pygame.mixer.music.load(cfg.BGM_PATH)
    pygame.mixer.music.play(-1, 30.0)
    # biu爱心那个背景图片
    bg_image = pygame.image.load(cfg.BG_IMAGE_PATH)
    bg_image = pygame.transform.smoothscale(bg_image, (150, 150))
    # 实例化两个按钮
    button_yes = Button(x=20, y=cfg.SCREENSIZE[1]-70, width=120, height=35, 
                        text='好呀', fontpath=cfg.FONT_PATH, fontsize=15, fontcolor=cfg.BLACK, edgecolor=cfg.SKYBLUE, 
                        edgesize=2, bgcolors=[cfg.DARKGRAY, cfg.GAINSBORO], is_want_to_be_selected=True, screensize=cfg.SCREENSIZE)
    button_no = Button(x=cfg.SCREENSIZE[0]-140, y=cfg.SCREENSIZE[1]-70, width=120, height=35, 
                       text='算了吧', fontpath=cfg.FONT_PATH, fontsize=15, fontcolor=cfg.BLACK, edgecolor=cfg.DARKGRAY, 
                       edgesize=1, bgcolors=[cfg.DARKGRAY, cfg.GAINSBORO], is_want_to_be_selected=False, screensize=cfg.SCREENSIZE)
    # 是否点击了好呀按钮
    is_agree = False
    # 主循环
    clock = pygame.time.Clock()
    while True:
        # --背景图片
        screen.fill(cfg.WHITE)
        screen.blit(bg_image, (cfg.SCREENSIZE[0]-bg_image.get_height(), 0))
        # --鼠标事件捕获
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                # ----没有点击好呀按钮之前不许退出程序
                if is_agree:
                    pygame.quit()
                    sys.exit()
            elif event.type == pygame.MOUSEBUTTONDOWN and event.button:
                if button_yes.rect.collidepoint(pygame.mouse.get_pos()):
                    button_yes.is_selected = True
                    root = Tk()
                    root.withdraw()
                    messagebox.showinfo('', '❤❤❤么么哒❤❤❤')
                    root.destroy()
                    is_agree = True
        # --显示文字
        showText(screen=screen, text='小姐姐, 我观察你很久了', position=(40, 50), 
                 fontpath=cfg.FONT_PATH, fontsize=25, fontcolor=cfg.BLACK, is_bold=False)
        showText(screen=screen, text='做我女朋友好不好?', position=(40, 100), 
                 fontpath=cfg.FONT_PATH, fontsize=25, fontcolor=cfg.BLACK, is_bold=True)
        # --显示按钮
        button_yes.draw(screen, pygame.mouse.get_pos())
        button_no.draw(screen, pygame.mouse.get_pos())
        # --刷新
        pygame.display.update()
        clock.tick(60)


'''run'''
if __name__ == '__main__':
    main()
love.py

 

4 添加自动化脚本GUI

# -*- coding: utf-8 -*-

import tkinter
from tkinter import ttk
from tkinter import scrolledtext
import datetime
import os
import time
from PIL import ImageGrab
import copy

class AutoFile:
    def __init__(self):
        self._listData = list()

    def readFile(self, strFilePath):
        ret = False
        self._listData.clear()
        with open(strFilePath, 'r') as fin:
            strLineData = fin.readline()
            while strLineData:
                strLineData = strLineData.strip('\n')  # 去除头尾的字符
                listOneData = strLineData.split(',')
                self._listData.append(listOneData)
                strLineData = fin.readline()
        if len(self._listData) > 0:
            ret = True
        return ret

    def writeFile(self, strFilePath):
        with open(strFilePath, 'w') as fout:
            for listOneData in self._listData:
                strLineData = listOneData[0] + ',' + listOneData[1] + '\n'
                fout.write(strLineData)
        return True

    def getListData(self):
        return self._listData

    def setListData(self, listData):
        self._listData.clear()
        self._listData = copy.deepcopy(listData)
        return None

    def getListDataSize(self):
        return len(self._listData)

    def delListData(self):
        return self._listData.clear()


# import pyscreenshot as ImageGrab

class FreeCapture():
    """ 用来显示全屏幕截图并响应二次截图的窗口类
    """

    def __init__(self, root, img, fileName):
        # 变量X和Y用来记录鼠标左键按下的位置
        self.X = tkinter.IntVar(value=0)
        self.Y = tkinter.IntVar(value=0)
        # 屏幕尺寸
        screenWidth = root.winfo_screenwidth()
        screenHeight = root.winfo_screenheight()
        # 创建顶级组件容器
        self.top = tkinter.Toplevel(root, width=screenWidth, height=screenHeight)
        # 不显示最大化、最小化按钮
        self.top.overrideredirect(True)
        self.canvas = tkinter.Canvas(self.top, bg='white', width=screenWidth, height=screenHeight)
        # 显示全屏截图,在全屏截图上进行区域截图
        self.image = tkinter.PhotoImage(file=img)
        self.canvas.create_image(screenWidth // 2, screenHeight // 2, image=self.image)
        self.fileName = fileName
        self.lastDraw = None

        # 鼠标左键按下的位置
        def onLeftButtonDown(event):
            self.X.set(event.x)
            self.Y.set(event.y)
            # 开始截图
            self.sel = True

        self.canvas.bind('<Button-1>', onLeftButtonDown)

        def onLeftButtonMove(event):
            # 鼠标左键移动,显示选取的区域
            if not self.sel:
                return
            try:  # 删除刚画完的图形,要不然鼠标移动的时候是黑乎乎的一片矩形
                self.canvas.delete(self.lastDraw)
            except Exception as e:
                pass
            self.lastDraw = self.canvas.create_rectangle(self.X.get(), self.Y.get(), event.x, event.y, outline='green')

        def onLeftButtonUp(event):
            # 获取鼠标左键抬起的位置,保存区域截图
            self.sel = False
            try:
                self.canvas.delete(self.lastDraw)
            except Exception as e:
                pass

            time.sleep(0.5)
            # 考虑鼠标左键从右下方按下而从左上方抬起的截图
            left, right = sorted([self.X.get(), event.x])
            top, bottom = sorted([self.Y.get(), event.y])
            pic = ImageGrab.grab((left + 1, top + 1, right, bottom))
            # 弹出保存截图对话框
            # self.fileName = tkinter.filedialog.asksaveasfilename(title='保存截图', filetypes=[('image', '*.jpg *.png')],defaultextension='.png')

            if self.fileName:
                pic.save(self.fileName)
            # 关闭当前窗口
            self.top.destroy()

        self.canvas.bind('<B1-Motion>', onLeftButtonMove)  # 按下左键
        self.canvas.bind('<ButtonRelease-1>', onLeftButtonUp)  # 抬起左键
        # 让canvas充满窗口,并随窗口自动适应大小
        self.canvas.pack(fill=tkinter.BOTH, expand=tkinter.YES)


def screenShot(root, fileName):
    """ 自由截屏的函数 (button按钮的事件)
    """
    #    print("test")
    root.state('icon')  # 最小化主窗体
    time.sleep(0.2)
    im = ImageGrab.grab()
    # 暂存全屏截图
    im.save('temp.png')
    im.close()
    # 进行自由截屏
    w = FreeCapture(root, 'temp.png', fileName)
    root.wait_window(w.top)
    # 截图结束,恢复主窗口,并删除temp.png文件
    root.state('normal')
    os.remove('temp.png')
    return w.top


class AutoWorkGUI(object):
    def __init__(self):
        
        self.listData = list()
        
        self.__tkTextBox_ListData = None  # tkinter控件--显示文本框
        self.__tkTextBox_FileName = None  # tkinter控件--输入框 [名称]
        self.__tkComboBox_Command = None  # tkinter控件--下拉框 [操作]
        self.__tkButon_SelectPath = None  # tkinter控件--按钮  [选择]
        self.__tkTextBox_ImgePath = None  # tkinter控件--输入框 [位置]
        self.__tkTextBox_InsertTx = None  # tkinter控件--输入框 [输入文本]
        self.__tkButon_AddOneData = None  # tkinter控件--按钮  [增加]
        self.__tkButon_MdyOneData = None  # tkinter控件--按钮  [修改]
        self.__tkButon_DelOneData = None  # tkinter控件--按钮  [删除]
        self.__tkButon_SaveFile   = None  # tkinter控件--按钮  [保存]
        self.__tkButon_OpenFile   = None  # tkinter控件--按钮  [打开]
        
        self.__win = tkinter.Tk()
        self.__win.bind_all('<Control-Key-1>', self._doSelect)
        self.__win.title("自动化办公--添加脚本")
        self.__win.geometry('900x560')
         # 把上面的win分成上下两个frame
        self.__frm_top = ttk.Frame(self.__win)
        self.__frm_bottom = ttk.Frame(self.__win)
        self.__frm_middle = ttk.Frame(self.__win)
        
        self.__frm_top.pack(side='top',fill='both')
        self.__frm_bottom.pack(side='bottom',fill='both')
        self.__frm_middle.pack(side='bottom',fill='both')
        
        self.__tkTextBox_ListData = scrolledtext.ScrolledText(self.__frm_top, width=100, height=27, font=("Courier New" ,12))
        self.__tkTextBox_ListData.bind("<Button-1>", self._leftButton)
        # 下部分
        lbName = ttk.Label(self.__frm_middle, text='脚本名称')
        self.__tkTextBox_FileName = ttk.Entry(self.__frm_middle)
        
        lbCommand = tkinter.Label(self.__frm_middle, text='操作')
        listValues = ['查找图标', '右击鼠标', '左击鼠标', '左双击', '右双击', '移动鼠标', '输入文字', 'ctrl+c', 'ctrl+v', '搜索', 'Enter', 'Tab']
        self.__tkComboBox_Command = ttk.Combobox(self.__frm_middle, values=listValues)
        
        lbPosion = tkinter.Label(self.__frm_middle, text='图标名称')
        self.__tkTextBox_ImgePath = ttk.Entry(self.__frm_middle)
        self.__tkButon_SelectPath = ttk.Button(self.__frm_middle, text='选择[Ctrl+1]', command=self._doSelect)
        
        lbInsert = tkinter.Label(self.__frm_middle, text='文本')
        self.__tkTextBox_InsertTx = ttk.Entry(self.__frm_middle)
        
        self.__tkButon_DelOneData = ttk.Button(self.__frm_bottom, text ="删除", command = self._doDelOneData,state="disable")  # 按钮
        self.__tkButon_MdyOneData = ttk.Button(self.__frm_bottom, text ="修改", command = self._doMdyOneData,state="disable")  # 按钮
        self.__tkButon_AddOneData = ttk.Button(self.__frm_bottom, text ="添加", command = self._doAddOneData)  # 按钮 
        self.__tkButon_SaveFile   = ttk.Button(self.__frm_bottom, text ="保存", command = self._doSaveFile)    # 按钮 
        self.__tkButon_OpenFile   = ttk.Button(self.__frm_bottom, text ="打开", command = self._doOpenFile,state="disable")
        
        #
        # 布局
        self.__tkTextBox_ListData.pack(fill='both')
        ### 
        lbName.pack(side='left' , padx=3, pady=5)
        self.__tkTextBox_FileName.pack(side='left', padx=2, pady=5)
        
        lbCommand.pack(side='left', padx=3, pady=5)
        self.__tkComboBox_Command.pack(side='left', padx=2, pady=5)
        lbPosion.pack(side='left', padx=3, pady=5)
        self.__tkTextBox_ImgePath.pack(side='left', padx=2, pady=5)
        self.__tkButon_SelectPath.pack(side='left', padx=2, pady=5)
        
        lbInsert.pack(side='left', padx=3, pady=5)
        self.__tkTextBox_InsertTx.pack(side='left', padx=2, pady=5)
        
        self.__tkButon_DelOneData.pack(side='left', padx=5, pady=5)
        self.__tkButon_MdyOneData.pack(side='left', padx=5, pady=5)
        self.__tkButon_AddOneData.pack(side='left', padx=5, pady=5)
        lbInfo = tkinter.Label(self.__frm_bottom, text='提示:脚本名称不支持中文')
        lbInfo.pack(side='left', padx=100, pady=5)
        self.__tkButon_SaveFile.pack(side='right', padx=5, pady=5)
        self.__tkButon_OpenFile.pack(side='right', padx=5, pady=5)
    
    def _leftButton(self, event):
        self.__tkTextBox_ListData.get
    
    def _doSelect(self, event=None):
        
        now = datetime.datetime.now()
        str1 = now.strftime("%H%M%S")
        str1 = str1+'.png'
        self.__tkTextBox_ImgePath.delete(0, tkinter.END)
        self.__tkTextBox_ImgePath.insert(0,str1)
        str2 = self.__tkTextBox_FileName.get()
        if '' == str2:
            tkinter.messagebox.showinfo('提示',"【名称】和【图标名称】不能为空!!")
            return None
        path = "Images/" + str2
        folder = os.path.exists(path)
        if not folder:                   #判断是否存在文件夹如果不存在则创建为文件夹
            os.makedirs(path)
        screenShot(self.__win, path + '/' +str1)
    
    def _doAddOneData(self):
        str1 = self.__tkTextBox_FileName.get()
        str2 = self.__tkTextBox_ImgePath.get()
        str3 = self.__tkTextBox_InsertTx.get()
        str4 = self.__tkComboBox_Command.get()
        if '' == str1:
            tkinter.messagebox.showinfo('提示',"【名称】不能为空!!")
            return None
        if '' == str4:
            tkinter.messagebox.showinfo('提示',"【操作】不能为空!!")
            return None
        
        str5 = str4+' '+str1+' '+str2+' '+str3
        self.listData.append([str4, str5])
        self.__tkTextBox_ListData.delete(1.0, tkinter.END) # 使用 delete
        for i in range(len(self.listData)):
            stri = str(i).zfill(3)
            strline = stri + " " +self.listData[i][1] + '\n'
            self.__tkTextBox_ListData.insert("insert", strline)
            
    def _doMdyOneData(self):
        pass
    
    def _doDelOneData(self):
        pass
    
    def _doSaveFile(self):
        str1 = self.__tkTextBox_FileName.get()
        if '' == str1:
            tkinter.messagebox.showinfo('提示',"【名称】不能为空!!")
            return None
        strPath = 'Drivers/'+ str1 + '.csv'
        handle = AutoFile()
        handle.setListData(self.listData)
        handle.writeFile(strPath)
        
        strPath1 = str1 + '.bat'
        with open(strPath1, 'w') as fout:
            fout.write("@echo off\n")
            fout.write("path = %path%;\n")
            fout.write("python main.py {}\n".format(strPath))
            fout.write("pause\n")
    
    def _doOpenFile(self):
        pass
    
    def show(self):
        # 显示主画面
        self.__win.mainloop()
    
def main():
     w = AutoWorkGUI()
     w.show()
if __name__ == '__main__':
    main()
     
     
     
     
     
     
     
     
     
     
     
     
     
     
     
gui.py

技术:tkinter, ScreenShot,  AutoFile

 

posted @ 2021-12-08 17:13  风hua  阅读(304)  评论(0编辑  收藏  举报