feat: add Tkinter GUI application for ERP automation tools
Implement a comprehensive GUI application with the following features: - Data Extraction tab: Extract material plan data from ERP system - Material Validation tab: Validate material status and match deletions - Data Query tab: Query database for production order information - Settings tab: Manage ERP, database, browser, and path configurations Key components: - MainWindow: Tabbed interface with status bar - ConfigManager: JSON-based configuration management - LogText: Custom read-only text widget with colored logging - FileSelector: Reusable file/directory selection component - ProgressDialog: Modal progress dialog for long operations Technical details: - Thread-safe UI updates using root.after() - Stdout capture for legacy script integration - Event-based readonly mode allowing copy/select operations - Custom widget composition to avoid Tkinter ScrolledText issues Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
10
gui/widgets/__init__.py
Normal file
10
gui/widgets/__init__.py
Normal file
@@ -0,0 +1,10 @@
|
||||
"""
|
||||
GUI 自定义组件模块
|
||||
|
||||
提供可复用的 UI 组件。
|
||||
"""
|
||||
|
||||
from .file_selector import FileSelector
|
||||
from .log_text import LogText
|
||||
|
||||
__all__ = ['FileSelector', 'LogText']
|
||||
96
gui/widgets/file_selector.py
Normal file
96
gui/widgets/file_selector.py
Normal file
@@ -0,0 +1,96 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
文件选择器组件
|
||||
|
||||
提供文件/目录选择功能的组合组件。
|
||||
"""
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import filedialog, ttk
|
||||
from typing import Optional, Callable
|
||||
|
||||
|
||||
class FileSelector(ttk.Frame):
|
||||
"""文件选择器组件"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
label_text: str = "",
|
||||
file_type: str = "file",
|
||||
file_types: list = None,
|
||||
initial_dir: str = "",
|
||||
on_change: Optional[Callable] = None
|
||||
):
|
||||
"""
|
||||
初始化文件选择器
|
||||
|
||||
Args:
|
||||
parent: 父容器
|
||||
label_text: 标签文本
|
||||
file_type: 选择类型 ('file' 或 'directory')
|
||||
file_types: 文件类型过滤器,如 [("Excel", "*.xlsx")]
|
||||
initial_dir: 初始目录
|
||||
on_change: 值改变时的回调函数
|
||||
"""
|
||||
super().__init__(parent)
|
||||
|
||||
self.file_type = file_type
|
||||
self.file_types = file_types or [("所有文件", "*.*")]
|
||||
self.initial_dir = initial_dir
|
||||
self.on_change = on_change
|
||||
|
||||
# 创建标签
|
||||
if label_text:
|
||||
self.label = ttk.Label(self, text=label_text)
|
||||
self.label.grid(row=0, column=0, sticky="w", padx=(0, 5))
|
||||
|
||||
# 创建输入框
|
||||
self.entry_var = tk.StringVar()
|
||||
self.entry = ttk.Entry(self, textvariable=self.entry_var, width=50)
|
||||
self.entry.grid(row=0, column=1, sticky="ew", padx=5)
|
||||
|
||||
# 创建浏览按钮
|
||||
self.browse_button = ttk.Button(self, text="浏览...", command=self._browse)
|
||||
self.browse_button.grid(row=0, column=2, padx=5)
|
||||
|
||||
# 配置列权重
|
||||
self.columnconfigure(1, weight=1)
|
||||
|
||||
def _browse(self) -> None:
|
||||
"""打开文件/目录选择对话框"""
|
||||
current_path = self.entry_var.get() or self.initial_dir
|
||||
|
||||
if self.file_type == "file":
|
||||
path = filedialog.askopenfilename(
|
||||
title="选择文件",
|
||||
initialdir=current_path,
|
||||
filetypes=self.file_types
|
||||
)
|
||||
else: # directory
|
||||
path = filedialog.askdirectory(
|
||||
title="选择目录",
|
||||
initialdir=current_path
|
||||
)
|
||||
|
||||
if path:
|
||||
self.entry_var.set(path)
|
||||
if self.on_change:
|
||||
self.on_change(path)
|
||||
|
||||
def get(self) -> str:
|
||||
"""获取当前选择的路径"""
|
||||
return self.entry_var.get()
|
||||
|
||||
def set(self, path: str) -> None:
|
||||
"""设置路径"""
|
||||
self.entry_var.set(path)
|
||||
|
||||
def clear(self) -> None:
|
||||
"""清空路径"""
|
||||
self.entry_var.set("")
|
||||
|
||||
def is_empty(self) -> bool:
|
||||
"""检查是否为空"""
|
||||
return not self.entry_var.get()
|
||||
180
gui/widgets/log_text.py
Normal file
180
gui/widgets/log_text.py
Normal file
@@ -0,0 +1,180 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
日志文本框组件
|
||||
|
||||
带颜色支持的日志显示组件。
|
||||
"""
|
||||
|
||||
import tkinter as tk
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class LogText(tk.Frame):
|
||||
"""日志文本框组件(带滚动条)"""
|
||||
|
||||
# 日志级别颜色配置
|
||||
LOG_COLORS = {
|
||||
'INFO': '#000000', # 黑色
|
||||
'SUCCESS': '#008000', # 绿色
|
||||
'WARNING': '#FF8C00', # 深橙色
|
||||
'ERROR': '#FF0000', # 红色
|
||||
'DEBUG': '#808080', # 灰色
|
||||
}
|
||||
|
||||
def __init__(self, parent, readonly=True, **kwargs):
|
||||
"""
|
||||
初始化日志文本框
|
||||
|
||||
Args:
|
||||
parent: 父容器
|
||||
readonly: 是否为只读模式
|
||||
**kwargs: 其他参数
|
||||
"""
|
||||
super().__init__(parent)
|
||||
|
||||
# 创建文本框和滚动条
|
||||
self.text = tk.Text(self, **kwargs)
|
||||
self.scrollbar = tk.Scrollbar(self, orient=tk.VERTICAL, command=self.text.yview)
|
||||
self.text.configure(yscrollcommand=self.scrollbar.set)
|
||||
|
||||
# 布局
|
||||
self.text.grid(row=0, column=0, sticky="nsew")
|
||||
self.scrollbar.grid(row=0, column=1, sticky="ns")
|
||||
|
||||
# 配置网格权重
|
||||
self.grid_rowconfigure(0, weight=1)
|
||||
self.grid_columnconfigure(0, weight=1)
|
||||
|
||||
# 标记 tags 是否已配置
|
||||
self._tags_configured = False
|
||||
|
||||
# 设置为只读模式
|
||||
if readonly:
|
||||
self._make_readonly()
|
||||
|
||||
def _ensure_tags_configured(self):
|
||||
"""确保文本标签已配置(延迟配置,在首次使用时)"""
|
||||
if not self._tags_configured:
|
||||
try:
|
||||
for level, color in self.LOG_COLORS.items():
|
||||
self.text.tag_config(level.lower(), foreground=color)
|
||||
self._tags_configured = True
|
||||
except Exception:
|
||||
# 如果配置失败,标记为已尝试,避免重复尝试
|
||||
self._tags_configured = True
|
||||
|
||||
def _make_readonly(self):
|
||||
"""通过绑定事件使文本框只读"""
|
||||
# 允许复制、全选等常用操作,阻止其他编辑操作
|
||||
self.text.bind('<Key>', self._handle_key)
|
||||
self.text.bind('<Button-1>', self._allow_click) # 允许左键点击选择
|
||||
|
||||
def _handle_key(self, event):
|
||||
"""处理按键事件,允许复制操作,阻止编辑"""
|
||||
# 允许的快捷键
|
||||
allowed_keys = [
|
||||
'Control-c', # 复制
|
||||
'Control-C', # 复制(大写)
|
||||
'Control-a', # 全选
|
||||
'Control-A', # 全选(大写)
|
||||
'Control-x', # 剪切(虽然剪不了,但不报错)
|
||||
'Control-X',
|
||||
]
|
||||
|
||||
# 检查是否是允许的快捷键
|
||||
key_sym = event.keysym
|
||||
state = event.state
|
||||
|
||||
# 检查 Ctrl 组合键
|
||||
if state & 0x4: # Ctrl 键被按下
|
||||
full_key = f"Control-{key_sym}"
|
||||
if full_key in allowed_keys:
|
||||
return # 允许执行
|
||||
|
||||
# 其他所有按键都阻止
|
||||
return 'break'
|
||||
|
||||
def _allow_click(self, event):
|
||||
"""允许点击和选择文本"""
|
||||
# 不打断事件,允许正常的选择操作
|
||||
return
|
||||
|
||||
def log(self, message: str, level: str = 'INFO') -> None:
|
||||
"""
|
||||
添加日志消息
|
||||
|
||||
Args:
|
||||
message: 日志消息
|
||||
level: 日志级别 (INFO, SUCCESS, WARNING, ERROR, DEBUG)
|
||||
"""
|
||||
# 确保 tags 已配置
|
||||
self._ensure_tags_configured()
|
||||
|
||||
timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
log_message = f"[{timestamp}] [{level}] {message}\n"
|
||||
|
||||
# 插入文本
|
||||
tag = level.lower() if self._tags_configured else None
|
||||
if tag:
|
||||
try:
|
||||
self.text.insert('end', log_message, (tag,))
|
||||
except Exception:
|
||||
# 如果带标签插入失败,尝试不带标签
|
||||
self.text.insert('end', log_message)
|
||||
else:
|
||||
self.text.insert('end', log_message)
|
||||
|
||||
# 自动滚动到底部
|
||||
self.text.see('end')
|
||||
|
||||
def info(self, message: str) -> None:
|
||||
"""添加 INFO 级别日志"""
|
||||
self.log(message, 'INFO')
|
||||
|
||||
def success(self, message: str) -> None:
|
||||
"""添加 SUCCESS 级别日志"""
|
||||
self.log(message, 'SUCCESS')
|
||||
|
||||
def warning(self, message: str) -> None:
|
||||
"""添加 WARNING 级别日志"""
|
||||
self.log(message, 'WARNING')
|
||||
|
||||
def error(self, message: str) -> None:
|
||||
"""添加 ERROR 级别日志"""
|
||||
self.log(message, 'ERROR')
|
||||
|
||||
def debug(self, message: str) -> None:
|
||||
"""添加 DEBUG 级别日志"""
|
||||
self.log(message, 'DEBUG')
|
||||
|
||||
def clear(self) -> None:
|
||||
"""清空日志"""
|
||||
self.text.delete('1.0', 'end')
|
||||
|
||||
def save_to_file(self, file_path: str) -> bool:
|
||||
"""
|
||||
保存日志到文件
|
||||
|
||||
Args:
|
||||
file_path: 保存路径
|
||||
|
||||
Returns:
|
||||
是否成功
|
||||
"""
|
||||
try:
|
||||
with open(file_path, 'w', encoding='utf-8') as f:
|
||||
f.write(self.text.get('1.0', 'end-1c'))
|
||||
return True
|
||||
except Exception as e:
|
||||
self.error(f"保存日志失败: {e}")
|
||||
return False
|
||||
|
||||
# 委托其他常用方法到内部 text 组件
|
||||
def pack(self, **kwargs):
|
||||
"""Pack 布局"""
|
||||
super().pack(**kwargs)
|
||||
|
||||
def grid(self, **kwargs):
|
||||
"""Grid 布局"""
|
||||
super().grid(**kwargs)
|
||||
120
gui/widgets/progress_dialog.py
Normal file
120
gui/widgets/progress_dialog.py
Normal file
@@ -0,0 +1,120 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
进度对话框组件
|
||||
|
||||
用于显示长时间运行操作的进度。
|
||||
"""
|
||||
|
||||
import tkinter as tk
|
||||
from tkinter import ttk
|
||||
from typing import Optional, Callable
|
||||
|
||||
|
||||
class ProgressDialog:
|
||||
"""进度对话框"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
parent,
|
||||
title: str = "处理中...",
|
||||
message: str = "请稍候",
|
||||
can_cancel: bool = True,
|
||||
on_cancel: Optional[Callable] = None
|
||||
):
|
||||
"""
|
||||
初始化进度对话框
|
||||
|
||||
Args:
|
||||
parent: 父窗口
|
||||
title: 对话框标题
|
||||
message: 显示消息
|
||||
can_cancel: 是否可以取消
|
||||
on_cancel: 取消回调函数
|
||||
"""
|
||||
self.parent = parent
|
||||
self.can_cancel = can_cancel
|
||||
self.on_cancel = on_cancel
|
||||
self.cancelled = False
|
||||
|
||||
# 创建对话框
|
||||
self.dialog = tk.Toplevel(parent)
|
||||
self.dialog.title(title)
|
||||
self.dialog.resizable(False, False)
|
||||
self.dialog.transient(parent)
|
||||
self.dialog.grab_set()
|
||||
|
||||
# 居中显示
|
||||
self._center()
|
||||
|
||||
# 创建内容
|
||||
self._create_widgets(message)
|
||||
|
||||
def _center(self):
|
||||
"""将对话框居中显示"""
|
||||
self.dialog.update_idletasks()
|
||||
width = 400
|
||||
height = 150
|
||||
x = (self.dialog.winfo_screenwidth() // 2) - (width // 2)
|
||||
y = (self.dialog.winfo_screenheight() // 2) - (height // 2)
|
||||
self.dialog.geometry(f"{width}x{height}+{x}+{y}")
|
||||
|
||||
def _create_widgets(self, message: str):
|
||||
"""创建对话框组件"""
|
||||
# 消息标签
|
||||
self.message_label = ttk.Label(self.dialog, text=message, wraplength=380)
|
||||
self.message_label.pack(pady=(20, 10), padx=20)
|
||||
|
||||
# 进度条
|
||||
self.progress = ttk.Progressbar(
|
||||
self.dialog,
|
||||
mode='indeterminate',
|
||||
length=360
|
||||
)
|
||||
self.progress.pack(pady=10, padx=20)
|
||||
self.progress.start(10)
|
||||
|
||||
# 取消按钮
|
||||
if self.can_cancel:
|
||||
button_frame = ttk.Frame(self.dialog)
|
||||
button_frame.pack(pady=10)
|
||||
|
||||
self.cancel_button = ttk.Button(
|
||||
button_frame,
|
||||
text="取消",
|
||||
command=self._on_cancel
|
||||
)
|
||||
self.cancel_button.pack()
|
||||
|
||||
def _on_cancel(self):
|
||||
"""处理取消操作"""
|
||||
self.cancelled = True
|
||||
if self.on_cancel:
|
||||
self.on_cancel()
|
||||
self.close()
|
||||
|
||||
def update_message(self, message: str):
|
||||
"""更新显示消息"""
|
||||
self.message_label.config(text=message)
|
||||
self.dialog.update_idletasks()
|
||||
|
||||
def set_progress(self, value: int, maximum: int = 100):
|
||||
"""
|
||||
设置进度值
|
||||
|
||||
Args:
|
||||
value: 当前进度值
|
||||
maximum: 最大值
|
||||
"""
|
||||
self.progress.config(mode='determinate', maximum=maximum)
|
||||
self.progress['value'] = value
|
||||
self.dialog.update_idletasks()
|
||||
|
||||
def close(self):
|
||||
"""关闭对话框"""
|
||||
self.progress.stop()
|
||||
self.dialog.destroy()
|
||||
|
||||
def is_cancelled(self) -> bool:
|
||||
"""检查是否已取消"""
|
||||
return self.cancelled
|
||||
Reference in New Issue
Block a user