PythonGUI实现文本转换、复制、顶置窗口等功能

需求描述:

  • 实现对文本的处理,比如输入123输出 ('123')
  • 窗口顶置、取消顶置功能
  • 一键清空文本内容、一键复制到剪切板

基于PYQT5

优点:使用灵活,组件调整简单,上手难度低;
缺点: 打包成exe文件占用大,启动慢;

源码

import re
import sys
from PyQt5 import QtCore
from PyQt5.Qt import *


class StrChangeOnQt5(QWidget):
    def __init__(self):
        super().__init__()
        # 设置窗口标题
        self.setWindowTitle("文本转换")
        # 禁止调整窗口大小
        self.setFixedSize(530, 750)
        # 设置窗口大小 可调整窗口大小
        # self.resize(530, 750)

        # 创建文本标签控件: 待转换文本
        self.labelTex1 = QLabel(self)
        # 为控件设置文本 待转换
        self.labelTex1.setText("待转换文本")
        # 字体样式设置
        self.labelTex1.setFont(QFont("黑体", 18, QFont.Bold))
        # 移动控件的位置
        self.labelTex1.move(50, 10)

        # 创建文本标签控件: 转换后文本
        self.labelTex2 = QLabel(self)
        # 为控件设置文本 待转换
        self.labelTex2.setText("转换后文本")
        # 字体样式设置
        self.labelTex2.setFont(QFont("黑体", 18, QFont.Bold))
        # 移动控件的位置
        self.labelTex2.move(350, 10)

        """多行文本框 待转换文本"""
        self.TextEdit1 = QTextEdit(self)
        # 设置字体颜色
        # self.TextEdit1.setTextColor(QColor(0, 0, 225))
        # 设置字体背景颜色
        # self.TextEdit1.setTextBackgroundColor(QColor(255, 0, 255))
        # 设置字体样式
        self.TextEdit1.setFont(QFont("TimesNewRoman", 14, QFont.Thin))
        # 水平滚动条
        # self.TextEdit1.setHorizontalScrollBar()
        # 移动控件的位置
        self.TextEdit1.move(20, 50)
        # 设置控件大小
        self.TextEdit1.resize(200, 600)

        """多行文本框 转换完文本"""
        self.TextEdit2 = QTextEdit(self)
        # 设置字体颜色
        # self.TextEdit2.setTextColor(QColor(0, 0, 225))
        # 设置字体背景颜色
        # self.TextEdit2.setTextBackgroundColor(QColor(255, 0, 255))
        # 设置字体样式
        self.TextEdit2.setFont(QFont("TimesNewRoman", 14, QFont.Thin))
        # 水平滚动条
        # self.TextEdit1.setHorizontalScrollBar()
        # 移动控件的位置
        self.TextEdit2.move(300, 50)
        # 设置控件大小
        self.TextEdit2.resize(200, 600)

        """转换按钮"""
        self.ChangeBtn = QPushButton(self)
        # 设置按钮文本
        self.ChangeBtn.setText("转 换")
        # 设置按钮位置
        self.ChangeBtn.move(20, 660)
        # 设置按钮大小
        self.ChangeBtn.resize(200, 50)
        # 设置按钮字体样式
        self.ChangeBtn.setFont(QFont("宋体", 14, QFont.Bold))

        """复制按钮"""
        self.CopyBtn = QPushButton(self)
        # 设置按钮文本
        self.CopyBtn.setText("复 制")
        # 设置按钮位置
        self.CopyBtn.move(300, 660)
        # 设置按钮大小
        self.CopyBtn.resize(200, 50)
        # 设置按钮字体样式
        self.CopyBtn.setFont(QFont("宋体", 14, QFont.Bold))

        """按钮"""
        self.TopBtn = QPushButton(self)
        # 设置按钮文本
        self.TopBtn.setText("顶置窗口")
        # 设置按钮位置
        self.TopBtn.move(230, 50)
        # 设置按钮大小
        self.TopBtn.resize(60, 30)
        # 设置按钮字体样式
        self.TopBtn.setFont(QFont("宋体", 10, QFont.Thin))

        """取消顶置按钮"""
        self.OffTopBtn = QPushButton(self)
        # 设置按钮文本
        self.OffTopBtn.setText("取消顶置")
        # 设置按钮位置
        self.OffTopBtn.move(230, 100)
        # 设置按钮大小
        self.OffTopBtn.resize(60, 30)
        # 设置按钮字体样式
        self.OffTopBtn.setFont(QFont("宋体", 10, QFont.Thin))

        """清除文本按钮"""
        self.ClearBtn = QPushButton(self)
        # 设置按钮文本
        self.ClearBtn.setText("清空内容")
        # 设置按钮位置
        self.ClearBtn.move(230, 150)
        # 设置按钮大小
        self.ClearBtn.resize(60, 30)
        # 设置按钮字体样式
        self.ClearBtn.setFont(QFont("宋体", 10, QFont.Thin))

        # 设置按钮事件
        # 转换按钮事件
        self.ChangeBtn.clicked.connect(self.ChangeTex)
        # 复制按钮事件
        self.CopyBtn.clicked.connect(self.CopyTex)
        # 置顶窗口按钮事件
        self.TopBtn.clicked.connect(self.TopWindow)
        # 取消置顶按钮事件
        self.OffTopBtn.clicked.connect(self.OffTopWindow)
        # 清空按钮事件
        self.ClearBtn.clicked.connect(self.ClearText)

    """点击转换按钮触发事件"""

    def ChangeTex(self):
        print("转换按钮被点击")
        gettext = self.TextEdit1.toPlainText().strip()
        # QMessageBox.warning(self,"警告! 文本为空!!")
        if len(gettext) == 0:
            self.TextEdit1.setPlaceholderText("请输入文本")
        else:
            print(gettext)
            subtext = "('" + re.sub("\\n", "','", gettext) + "')"
            print("转换完后文本:" + subtext)
            self.TextEdit2.setText(subtext)

    """复制按钮触事件"""

    def CopyTex(self):
        print("复制按钮被点击")
        gettext1 = self.TextEdit2.toPlainText()
        self.TextEdit2.setFocus()
        self.TextEdit2.selectAll()
        self.TextEdit2.copy()

    """置顶窗口按钮触发事件"""

    def TopWindow(self):
        # 设置窗口置顶
        self.setWindowFlags(QtCore.Qt.WindowStaysOnTopHint)
        self.setVisible(True)

    """取消置顶按钮触发事件"""

    def OffTopWindow(self):
        # 取消窗口置顶
        self.setWindowFlags(QtCore.Qt.Widget)
        self.setVisible(True)

    """清空文本按钮触发事件"""

    def ClearText(self):
        self.TextEdit1.clear()
        self.TextEdit2.clear()


if __name__ == '__main__':
    # 创建一个应用程序对象
    app = QApplication(sys.argv)
    # 创建一个空白控件(窗口)
    window = StrChangeOnQt5()
    # 显示窗口
    window.show()
    # 进入程序主循环,通过exit函数确保主循环安全结束
    sys.exit(app.exec_())

效果图

image

基于tkinter

优点:上手难度较高,界面有点古老,组件微调困难;
缺点: Python自带库,启动资源小,效率高;

源码

import re
import tkinter as tk
from tkinter import messagebox, INSERT

# 设置窗口居中
def center_window(window, width, height):
    # 获取显示屏宽度
    screenwidth = window.winfo_screenwidth()
    # 获取显示屏高度
    screenheight = window.winfo_screenheight()
    # 设置窗口居中参数
    size = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
    # 设置窗口位置
    window.geometry(size)


# 实例化object 建立窗口window
window = tk.Tk()
# 窗口标题
window.title("文本转换")
# 设置窗口大小且居中
center_window(window, 530, 750)

# 设置禁止缩放
window.resizable(False, False)

# 设置文本标签1 待转换文本
labelText1 = tk.Label(window, text='待转换文本', font=('黑体', 16, 'bold'))
# 放置文本标签1
labelText1.place(x=50, y=10)

# 设置文本标签2 转换完文本
labelText1 = tk.Label(window, text='转换完文本', font=('黑体', 16, 'bold'))
# 放置文本标签2
labelText1.place(x=350, y=10)

# 文本框1 待转换文本
# width 一行可见的字符数  height显示的行数
text1 = tk.Text(window, width=20, height=30, font=('TimesNewRoman', 14))
# 创建Scrollbar对象
scroll1 = tk.Scrollbar(window, orient='vertical')
scroll1.place(x=220, y=50, height=580)
text1.place(x=20, y=50)
scroll1.config(command=text1.yview)
text1.config(yscrollcommand=scroll1.set)

# 文本框2 转换完文本
# width 一行可见的字符数  height显示的行数
text2 = tk.Text(window, width=20, height=30, font=('TimesNewRoman', 14))
# 创建Scrollbar对象
scroll2 = tk.Scrollbar(window, orient='vertical')
scroll2.place(x=515, y=50, height=580)
text2.place(x=320, y=50)
scroll2.config(command=text2.yview)
text2.config(yscrollcommand=scroll2.set)


# 点击转换按钮触发事件
def ChangeTex():
    print("转换按钮被点击")
    gettext1 = text1.get('1.0', 'end').strip()
    if len(gettext1) == 0:
        print("输入 为空")
        messagebox.showinfo("提示", "请输入文本")
    else:
        print(gettext1)
        subtext = "('" + re.sub("\\n", "','", gettext1) + "')"
        # 先清空内容再插入实现覆盖操作
        text2.delete('1.0', 'end')
        text2.insert(INSERT, subtext)
        # 设置焦点选中效果
        text2.focus_set()
        text2.tag_add('sel', '1.0', 'end')
        print(subtext)


# 点击复制按钮触发事件
def CopyTex():
    gettext2 = text2.get('1.0', 'end').strip()
    # 复制到剪切板
    text2.clipboard_clear()
    text2.clipboard_append(gettext2)


# 点击置顶窗口按钮触发事件
def TopWindow():
    window.attributes('-topmost', True)


# 点击取消置顶按钮触发事件
def OffWindow():
    window.attributes('-topmost', False)


# 点击清空文本按钮触发事件
def ClearText():
    text1.delete('1.0', 'end')
    text2.delete('1.0', 'end')


# 转换按钮
ChangeBtn = tk.Button(window, text='转 换', font=('宋体', 16, 'bold'), width=16, height=2, command=ChangeTex)
ChangeBtn.place(x=20, y=660)

# 复制按钮
ChangeBtn = tk.Button(window, text='复 制', font=('宋体', 16, 'bold'), width=16, height=2, command=CopyTex)
ChangeBtn.place(x=320, y=660)

# 置顶窗口按钮
ChangeBtn = tk.Button(window, text='置顶窗口', font=('宋体', 10),  width=8, height=1, command=TopWindow)
ChangeBtn.place(x=240, y=50)

# 取消置顶按钮
ChangeBtn = tk.Button(window, text='取消置顶', font=('宋体', 10),  width=8, height=1, command=OffWindow)
ChangeBtn.place(x=240, y=100)

# 清空文本按钮
ChangeBtn = tk.Button(window, text='清空文本', font=('宋体', 10), width=8, height=1, command=ClearText)
ChangeBtn.place(x=240, y=150)

window.mainloop()

效果图:
image

后续可优化:

  • 添加图标
  • 字体优化
  • 按钮位置调整
  • 自动缩放

2026.2月更新

  • 让AI优化并适应高分屏,花了10分钟,太强了
import tkinter as tk
from tkinter import messagebox, INSERT, font
import re
import ctypes
import sys

class HighDPITextConverter:
    def __init__(self):
        # Windows高DPI适配
        if sys.platform == 'win32':
            try:
                ctypes.windll.shcore.SetProcessDpiAwareness(1)
            except:
                try:
                    ctypes.windll.user32.SetProcessDPIAware()
                except:
                    pass
        
        self.window = tk.Tk()
        self.window.title("文本转换器 · 高DPI版")
        
        # 获取屏幕尺寸
        self.screenwidth = self.window.winfo_screenwidth()
        self.screenheight = self.window.winfo_screenheight()
        
        # 窗口大小
        if self.screenwidth >= 2560:  # 2K或更高
            self.window_width = 1400
            self.window_height = 900
        elif self.screenwidth >= 1920:  # 全高清
            self.window_width = 1200
            self.window_height = 800
        else:  # 较低分辨率
            self.window_width = 1000
            self.window_height = 700
        
        # 居中显示
        x = (self.screenwidth - self.window_width) // 2
        y = (self.screenheight - self.window_height) // 2
        
        self.window.geometry(f'{self.window_width}x{self.window_height}+{x}+{y}')
        self.window.configure(bg='#f5f7fa')
        
        # 允许窗口缩放
        self.window.resizable(True, True)
        self.window.minsize(800, 600)
        
        # 配色方案
        self.colors = {
            'bg_primary': '#f5f7fa',
            'bg_secondary': '#ffffff',
            'accent': '#4361ee',
            'accent_light': '#4895ef',
            'success': '#4cc9f0',
            'warning': '#f72585',
            'text_primary': '#2b2d42',
            'text_secondary': '#8d99ae',
            'border': '#e9ecef'
        }
        
        # 设置字体
        self.setup_fonts()
        
        # 初始化UI
        self.setup_ui()
    
    def setup_fonts(self):
        """设置字体"""
        if self.screenwidth >= 2560:
            base_size = 12
            title_size = 18
            small_size = 10
        elif self.screenwidth >= 1920:
            base_size = 11
            title_size = 16
            small_size = 9
        else:
            base_size = 10
            title_size = 14
            small_size = 8
        
        try:
            self.title_font = font.Font(family='Microsoft YaHei', size=title_size, weight='bold')
            self.normal_font = font.Font(family='Microsoft YaHei', size=base_size)
            self.small_font = font.Font(family='Microsoft YaHei', size=small_size)
            self.text_font = font.Font(family='Consolas', size=base_size)
        except:
            self.title_font = font.Font(family='Arial', size=title_size, weight='bold')
            self.normal_font = font.Font(family='Arial', size=base_size)
            self.small_font = font.Font(family='Arial', size=small_size)
            self.text_font = font.Font(family='Courier New', size=base_size)
    
    def create_text_area(self, parent, label_text):
        """创建带滚动条的文本区域"""
        # 框架
        frame = tk.Frame(parent, bg=self.colors['bg_primary'])
        frame.pack(fill='both', expand=True)
        
        # 标签
        label = tk.Label(
            frame,
            text=label_text,
            font=self.normal_font,
            bg=self.colors['bg_primary'],
            fg=self.colors['text_primary'],
            anchor='w'
        )
        label.pack(anchor='w', pady=(0, 5))
        
        # 文本框框架(包含文本框和滚动条)
        text_frame = tk.Frame(frame, bg=self.colors['bg_primary'])
        text_frame.pack(fill='both', expand=True)
        
        # 文本框
        text_widget = tk.Text(
            text_frame,
            font=self.text_font,
            bg=self.colors['bg_secondary'],
            fg=self.colors['text_primary'],
            relief='solid',
            bd=1,
            padx=8,
            pady=8,
            wrap='word',
            highlightbackground=self.colors['border'],
            highlightcolor=self.colors['accent'],
            highlightthickness=1,
            insertbackground=self.colors['accent']
        )
        text_widget.pack(side='left', fill='both', expand=True)
        
        # 垂直滚动条
        v_scrollbar = tk.Scrollbar(
            text_frame, 
            orient='vertical', 
            command=text_widget.yview,
            bg=self.colors['border'],
            activebackground=self.colors['accent'],
            troughcolor=self.colors['bg_primary'],
            width=16  # 稍微宽一点,更容易点击
        )
        v_scrollbar.pack(side='right', fill='y')
        text_widget.config(yscrollcommand=v_scrollbar.set)
        
        # 水平滚动条(可选,当文本很长时使用)
        h_scrollbar = tk.Scrollbar(
            frame,
            orient='horizontal',
            command=text_widget.xview,
            bg=self.colors['border'],
            activebackground=self.colors['accent'],
            troughcolor=self.colors['bg_primary']
        )
        # 默认不显示水平滚动条,只在需要时显示
        text_widget.config(xscrollcommand=h_scrollbar.set)
        
        return frame, text_widget, v_scrollbar, h_scrollbar
    
    def setup_ui(self):
        """设置UI"""
        # 使用grid布局
        self.window.grid_rowconfigure(1, weight=1)
        self.window.grid_columnconfigure(0, weight=1)
        self.window.grid_columnconfigure(1, weight=0)  # 中间控制列不扩展
        self.window.grid_columnconfigure(2, weight=1)
        
        # 标题栏
        title_frame = tk.Frame(self.window, bg=self.colors['bg_primary'], height=50)
        title_frame.grid(row=0, column=0, columnspan=3, sticky='ew', padx=20, pady=(15, 5))
        title_frame.grid_propagate(False)
        
        title_label = tk.Label(
            title_frame,
            text="✨ 文本转换器",
            font=self.title_font,
            bg=self.colors['bg_primary'],
            fg=self.colors['text_primary']
        )
        title_label.pack(side='left')
        
        subtitle_label = tk.Label(
            title_frame,
            text="将多行文本转换为SQL元组格式",
            font=self.normal_font,
            bg=self.colors['bg_primary'],
            fg=self.colors['text_secondary']
        )
        subtitle_label.pack(side='left', padx=(10, 0))
        
        # 主内容区域
        main_frame = tk.Frame(self.window, bg=self.colors['bg_primary'])
        main_frame.grid(row=1, column=0, columnspan=3, sticky='nsew', padx=20, pady=5)
        main_frame.grid_columnconfigure(0, weight=1)
        main_frame.grid_columnconfigure(1, weight=0)
        main_frame.grid_columnconfigure(2, weight=1)
        main_frame.grid_rowconfigure(0, weight=1)
        
        # ========== 左侧输入区域 ==========
        left_frame = tk.Frame(main_frame, bg=self.colors['bg_primary'])
        left_frame.grid(row=0, column=0, sticky='nsew', padx=(0, 5))
        left_frame.grid_rowconfigure(1, weight=1)
        left_frame.grid_columnconfigure(0, weight=1)
        
        # 输入标签
        input_label = tk.Label(
            left_frame,
            text="📝 输入文本",
            font=self.normal_font,
            bg=self.colors['bg_primary'],
            fg=self.colors['text_primary'],
            anchor='w'
        )
        input_label.grid(row=0, column=0, sticky='w', pady=(0, 5))
        
        # 输入文本框框架
        input_text_frame = tk.Frame(left_frame, bg=self.colors['bg_primary'])
        input_text_frame.grid(row=1, column=0, sticky='nsew')
        input_text_frame.grid_rowconfigure(0, weight=1)
        input_text_frame.grid_columnconfigure(0, weight=1)
        
        # 输入文本框
        self.text_input = tk.Text(
            input_text_frame,
            font=self.text_font,
            bg=self.colors['bg_secondary'],
            fg=self.colors['text_primary'],
            relief='solid',
            bd=1,
            padx=8,
            pady=8,
            wrap='word',
            highlightbackground=self.colors['border'],
            highlightcolor=self.colors['accent'],
            highlightthickness=1,
            insertbackground=self.colors['accent']
        )
        self.text_input.grid(row=0, column=0, sticky='nsew')
        
        # 输入框垂直滚动条
        input_v_scroll = tk.Scrollbar(
            input_text_frame,
            orient='vertical',
            command=self.text_input.yview,
            bg=self.colors['border'],
            activebackground=self.colors['accent'],
            troughcolor=self.colors['bg_primary'],
            width=16
        )
        input_v_scroll.grid(row=0, column=1, sticky='ns')
        self.text_input.config(yscrollcommand=input_v_scroll.set)
        
        # 输入框水平滚动条
        input_h_scroll = tk.Scrollbar(
            left_frame,
            orient='horizontal',
            command=self.text_input.xview,
            bg=self.colors['border'],
            activebackground=self.colors['accent'],
            troughcolor=self.colors['bg_primary']
        )
        # 默认隐藏,只有在需要时才显示
        input_h_scroll.grid(row=2, column=0, sticky='ew')
        input_h_scroll.grid_remove()  # 初始隐藏
        self.text_input.config(xscrollcommand=lambda *args: self.toggle_h_scrollbar(input_h_scroll, *args))
        
        # 字符计数
        self.char_count_label = tk.Label(
            left_frame,
            text="0 字符 | 0 行",
            font=self.small_font,
            bg=self.colors['bg_primary'],
            fg=self.colors['text_secondary']
        )
        self.char_count_label.grid(row=3, column=0, sticky='e', pady=(5, 0))
        self.text_input.bind('<KeyRelease>', self.update_char_count)
        
        # ========== 中间控制区域 ==========
        control_frame = tk.Frame(main_frame, bg=self.colors['bg_primary'], width=120)
        control_frame.grid(row=0, column=1, sticky='ns', padx=10)
        control_frame.grid_propagate(False)
        
        # 垂直居中
        control_inner = tk.Frame(control_frame, bg=self.colors['bg_primary'])
        control_inner.pack(expand=True)
        
        # 转换按钮
        convert_btn = tk.Button(
            control_inner,
            text="→ 转 换 →",
            font=self.normal_font,
            command=self.change_text,
            bg=self.colors['accent'],
            fg='white',
            relief='flat',
            bd=0,
            padx=15,
            pady=10,
            cursor='hand2',
            activebackground=self.colors['accent_light'],
            activeforeground='white'
        )
        convert_btn.pack(pady=8)
        convert_btn.bind('<Enter>', lambda e: convert_btn.config(bg=self.colors['accent_light']))
        convert_btn.bind('<Leave>', lambda e: convert_btn.config(bg=self.colors['accent']))
        
        # 其他按钮
        buttons = [
            ('📋 复 制', self.copy_text, self.colors['success'], 'white'),
            ('🗑️ 清 空', self.clear_text, self.colors['warning'], 'white'),
            ('📌 置 顶', self.top_window, self.colors['bg_secondary'], self.colors['text_primary']),
            ('🔓 取消置顶', self.off_window, self.colors['bg_secondary'], self.colors['text_primary'])
        ]
        
        for text, cmd, bg_color, fg_color in buttons:
            btn = tk.Button(
                control_inner,
                text=text,
                font=self.small_font,
                command=cmd,
                bg=bg_color,
                fg=fg_color,
                relief='flat',
                bd=1,
                padx=10,
                pady=6,
                cursor='hand2',
                activebackground=self.colors['border'],
                activeforeground=self.colors['text_primary']
            )
            btn.pack(pady=3, fill='x')
        
        # ========== 右侧输出区域 ==========
        right_frame = tk.Frame(main_frame, bg=self.colors['bg_primary'])
        right_frame.grid(row=0, column=2, sticky='nsew', padx=(5, 0))
        right_frame.grid_rowconfigure(1, weight=1)
        right_frame.grid_columnconfigure(0, weight=1)
        
        # 输出标签
        output_label = tk.Label(
            right_frame,
            text="🎯 输出结果",
            font=self.normal_font,
            bg=self.colors['bg_primary'],
            fg=self.colors['text_primary'],
            anchor='w'
        )
        output_label.grid(row=0, column=0, sticky='w', pady=(0, 5))
        
        # 输出文本框框架
        output_text_frame = tk.Frame(right_frame, bg=self.colors['bg_primary'])
        output_text_frame.grid(row=1, column=0, sticky='nsew')
        output_text_frame.grid_rowconfigure(0, weight=1)
        output_text_frame.grid_columnconfigure(0, weight=1)
        
        # 输出文本框
        self.text_output = tk.Text(
            output_text_frame,
            font=self.text_font,
            bg=self.colors['bg_secondary'],
            fg=self.colors['text_primary'],
            relief='solid',
            bd=1,
            padx=8,
            pady=8,
            wrap='word',
            highlightbackground=self.colors['border'],
            highlightcolor=self.colors['accent'],
            highlightthickness=1,
            insertbackground=self.colors['accent']
        )
        self.text_output.grid(row=0, column=0, sticky='nsew')
        
        # 输出框垂直滚动条
        output_v_scroll = tk.Scrollbar(
            output_text_frame,
            orient='vertical',
            command=self.text_output.yview,
            bg=self.colors['border'],
            activebackground=self.colors['accent'],
            troughcolor=self.colors['bg_primary'],
            width=16
        )
        output_v_scroll.grid(row=0, column=1, sticky='ns')
        self.text_output.config(yscrollcommand=output_v_scroll.set)
        
        # 输出框水平滚动条
        output_h_scroll = tk.Scrollbar(
            right_frame,
            orient='horizontal',
            command=self.text_output.xview,
            bg=self.colors['border'],
            activebackground=self.colors['accent'],
            troughcolor=self.colors['bg_primary']
        )
        output_h_scroll.grid(row=2, column=0, sticky='ew')
        output_h_scroll.grid_remove()  # 初始隐藏
        self.text_output.config(xscrollcommand=lambda *args: self.toggle_h_scrollbar(output_h_scroll, *args))
        
        # 复制提示
        self.copy_hint = tk.Label(
            right_frame,
            text="点击复制按钮或按 Ctrl+C 复制结果",
            font=self.small_font,
            bg=self.colors['bg_primary'],
            fg=self.colors['text_secondary']
        )
        self.copy_hint.grid(row=3, column=0, sticky='e', pady=(5, 0))
        
        # ========== 底部状态栏 ==========
        status_frame = tk.Frame(self.window, bg=self.colors['bg_secondary'], height=35)
        status_frame.grid(row=2, column=0, columnspan=3, sticky='ew', padx=20, pady=(10, 15))
        status_frame.grid_propagate(False)
        
        self.status_label = tk.Label(
            status_frame,
            text="✨ 就绪",
            font=self.small_font,
            bg=self.colors['bg_secondary'],
            fg=self.colors['text_secondary']
        )
        self.status_label.pack(side='left', padx=15)
        
        version_label = tk.Label(
            status_frame,
            text="v2.0 · 高DPI版",
            font=self.small_font,
            bg=self.colors['bg_secondary'],
            fg=self.colors['text_secondary']
        )
        version_label.pack(side='right', padx=15)
        
        # 绑定快捷键
        self.window.bind('<Control-Return>', lambda e: self.change_text())
        self.window.bind('<Control-c>', lambda e: self.copy_text())
        self.window.bind('<Control-d>', lambda e: self.clear_text())
        
        # 绑定窗口大小改变事件
        self.window.bind('<Configure>', self.on_window_resize)
        
        # 初始化
        self.update_char_count()
    
    def toggle_h_scrollbar(self, scrollbar, first, last):
        """控制水平滚动条的显示/隐藏"""
        if float(first) <= 0.0 and float(last) >= 1.0:
            scrollbar.grid_remove()
        else:
            scrollbar.grid()
        scrollbar.set(first, last)
    
    def on_window_resize(self, event):
        """窗口大小改变时的处理"""
        if event.widget == self.window:
            # 可以在这里根据需要调整字体大小
            pass
    
    def update_char_count(self, event=None):
        """更新字符计数"""
        content = self.text_input.get('1.0', 'end-1c')
        char_count = len(content)
        line_count = len(content.split('\n')) if content else 0
        self.char_count_label.config(text=f"{char_count} 字符 | {line_count} 行")
    
    def change_text(self):
        """转换文本"""
        content = self.text_input.get('1.0', 'end-1c').strip()
        if not content:
            messagebox.showinfo("提示", "请输入要转换的文本")
            return
        
        lines = [line.strip() for line in content.split('\n') if line.strip()]
        result = "('" + "','".join(lines) + "')"
        
        self.text_output.delete('1.0', 'end')
        self.text_output.insert('1.0', result)
        self.text_output.tag_add('sel', '1.0', 'end')
        
        self.status_label.config(text=f"✅ 转换完成,共处理 {len(lines)} 行")
    
    def copy_text(self):
        """复制结果"""
        result = self.text_output.get('1.0', 'end-1c').strip()
        if result:
            self.window.clipboard_clear()
            self.window.clipboard_append(result)
            self.status_label.config(text="📋 已复制到剪贴板")
            
            self.copy_hint.config(text="✓ 复制成功!", fg=self.colors['success'])
            self.window.after(2000, lambda: self.copy_hint.config(
                text="点击复制按钮或按 Ctrl+C 复制结果", 
                fg=self.colors['text_secondary']
            ))
    
    def clear_text(self):
        """清空所有文本"""
        self.text_input.delete('1.0', 'end')
        self.text_output.delete('1.0', 'end')
        self.update_char_count()
        self.status_label.config(text="🗑️ 文本已清空")
    
    def top_window(self):
        """窗口置顶"""
        self.window.attributes('-topmost', True)
        self.status_label.config(text="📌 窗口已置顶")
    
    def off_window(self):
        """取消置顶"""
        self.window.attributes('-topmost', False)
        self.status_label.config(text="🔓 已取消置顶")
    
    def run(self):
        self.window.mainloop()

if __name__ == "__main__":
    app = HighDPITextConverter()
    app.run()


效果图:
image

posted @ 2024-03-05 22:31  坤坤呀  阅读(171)  评论(0)    收藏  举报