62 lines
2.2 KiB
Python
62 lines
2.2 KiB
Python
import tkinter as tk
|
|
|
|
class ProgressButton(tk.Canvas):
|
|
def __init__(self, master, text="", command=None, **kwargs):
|
|
bg = kwargs.pop('bg', '#e1e1e1')
|
|
height = kwargs.pop('height', 32)
|
|
cursor = kwargs.pop('cursor', 'hand2')
|
|
super().__init__(master, bg=bg, highlightthickness=1, highlightbackground="#cccccc", highlightcolor="#cccccc", height=height, cursor=cursor, **kwargs)
|
|
self.command = command
|
|
self.progress = 0.0
|
|
|
|
self.bg_color = bg
|
|
self.fill_color = "#4caf50"
|
|
self.hover_color = "#d5d5d5"
|
|
|
|
self.rect_id = self.create_rectangle(0, 0, 0, 0, fill=self.fill_color, width=0)
|
|
self.text_id = self.create_text(0, 0, text=text, fill="black", font=("Microsoft YaHei", 10))
|
|
|
|
self.bind("<Button-1>", self._on_click)
|
|
self.bind("<Enter>", self._on_enter)
|
|
self.bind("<Leave>", self._on_leave)
|
|
self.bind("<Configure>", self._on_resize)
|
|
|
|
def _on_click(self, event):
|
|
if self.command:
|
|
self.command()
|
|
|
|
def _on_enter(self, event):
|
|
self.config(bg=self.hover_color)
|
|
|
|
def _on_leave(self, event):
|
|
self.config(bg=self.bg_color)
|
|
|
|
def _on_resize(self, event):
|
|
self._update_layout()
|
|
|
|
def _update_layout(self):
|
|
w = self.winfo_width()
|
|
h = self.winfo_height()
|
|
self.coords(self.rect_id, 0, 0, w * self.progress, h)
|
|
self.coords(self.text_id, w / 2, h / 2)
|
|
|
|
def config_btn(self, text=None, command=None, state=None):
|
|
if text is not None:
|
|
self.itemconfig(self.text_id, text=text)
|
|
if command is not None:
|
|
self.command = command
|
|
if state == tk.DISABLED:
|
|
self.config(cursor="arrow", bg=self.bg_color)
|
|
self.unbind("<Button-1>")
|
|
self.unbind("<Enter>")
|
|
self.unbind("<Leave>")
|
|
elif state == tk.NORMAL:
|
|
self.config(cursor="hand2")
|
|
self.bind("<Button-1>", self._on_click)
|
|
self.bind("<Enter>", self._on_enter)
|
|
self.bind("<Leave>", self._on_leave)
|
|
|
|
def set_progress(self, percent):
|
|
self.progress = percent
|
|
self._update_layout()
|