-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui_widgets.py
More file actions
55 lines (41 loc) · 1.85 KB
/
gui_widgets.py
File metadata and controls
55 lines (41 loc) · 1.85 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# gui_widgets.py
import tkinter as tk
from tkinter import ttk
class FormattedLabel(ttk.Label):
"""格式化标签控件,用于显示数值。"""
def __init__(self, parent, textvariable, precision=1, **kwargs):
self.var = textvariable
self.precision = precision
self.str_var = tk.StringVar()
super().__init__(parent, textvariable=self.str_var, **kwargs)
self.var.trace_add("write", self._update_text)
self._update_text()
def _update_text(self, *args):
try:
self.str_var.set(f"{self.var.get():.{self.precision}f}")
except (ValueError, tk.TclError):
self.str_var.set("")
class ScrollableFrame(ttk.Frame):
"""可滚动的Frame控件。"""
def __init__(self, container, *args, **kwargs):
super().__init__(container, *args, **kwargs)
self.canvas = tk.Canvas(self)
scrollbar = ttk.Scrollbar(self, orient="vertical", command=self.canvas.yview)
self.content_frame = ttk.Frame(self.canvas)
self.content_frame.bind(
"<Configure>",
lambda e: self.canvas.configure(scrollregion=self.canvas.bbox("all"))
)
self.canvas.create_window((0, 0), window=self.content_frame, anchor="nw")
self.canvas.configure(yscrollcommand=scrollbar.set)
self._bind_mouse_wheel_to_children(self)
self.canvas.grid(row=0, column=0, sticky="nsew")
scrollbar.grid(row=0, column=1, sticky="ns")
self.grid_rowconfigure(0, weight=1)
self.grid_columnconfigure(0, weight=1)
def _on_mouse_wheel(self, event):
self.canvas.yview_scroll(int(-1 * (event.delta / 120)), "units")
def _bind_mouse_wheel_to_children(self, widget):
widget.bind("<MouseWheel>", self._on_mouse_wheel)
for child in widget.winfo_children():
self._bind_mouse_wheel_to_children(child)