如何让Tkinter带滚动条的文本框可通过鼠标拖动调整大小?
实现可拖动调整大小的带滚动条文本框
方法1:使用PanedWindow组件(快速实现)
PanedWindow是Tkinter内置的支持拖动调整子组件尺寸的容器,只需替换原代码中的普通Frame即可实现需求:
import tkinter as tk import sys class Redirect(): def __init__(self, widget, autoscroll=True): self.widget = widget self.autoscroll = autoscroll self.output = widget def write(self, text): self.widget.insert('end', text) if self.autoscroll: self.widget.see("end") self.output.update_idletasks() root = tk.Tk() root.geometry("1200x620+1+1") # 替换普通Frame为PanedWindow,允许拖动调整大小 paned_frame = tk.PanedWindow(root, orient=tk.VERTICAL) paned_frame.place(x=650, y=310, anchor="c", width=850, height=400) # 文本框容器放入PanedWindow text_frame = tk.Frame(paned_frame) paned_frame.add(text_frame) text=tk.Text(text_frame, width=25, height=8, wrap='word') text.pack(side='left', fill='both', expand=True ) scrollbar = tk.Scrollbar(text_frame) scrollbar.pack(side='right', fill='y') text['yscrollcommand'] = scrollbar.set scrollbar['command'] = text.yview old_stdout = sys.stdout sys.stdout = Redirect(text) root.mainloop() sys.stdout = old_stdout
- 拖动PanedWindow显示的分隔线即可调整文本框区域大小
- 若需横向调整,将
orient=tk.VERTICAL改为tk.HORIZONTAL
方法2:手动实现边缘拖动(自定义程度高)
如果需要支持拖动任意边缘调整大小,可通过绑定鼠标事件自定义实现:
import tkinter as tk import sys class Redirect(): def __init__(self, widget, autoscroll=True): self.widget = widget self.autoscroll = autoscroll self.output = widget def write(self, text): self.widget.insert('end', text) if self.autoscroll: self.widget.see("end") self.output.update_idletasks() class ResizableFrame(tk.Frame): def __init__(self, parent, *args, **kwargs): super().__init__(parent, *args, **kwargs) self.bind("<Button-1>", self.start_resize) self.bind("<B1-Motion>", self.resize) # 定义边缘可拖动区域宽度(像素) self.resize_border = 10 def start_resize(self, event): # 记录初始状态 self.start_x = event.x self.start_y = event.y self.start_width = self.winfo_width() self.start_height = self.winfo_height() def resize(self, event): # 计算新尺寸并限制最小值 new_width = self.start_width + (event.x - self.start_x) new_height = self.start_height + (event.y - self.start_y) if new_width > 100 and new_height > 50: self.config(width=new_width, height=new_height) root = tk.Tk() root.geometry("1200x620+1+1") # 使用自定义可拖动Frame frame = ResizableFrame(root) frame.place(x=650, y=310, anchor="c", width=850, height=400 ) text=tk.Text(frame, width=25, height=8, wrap='word') text.pack(side='left', fill='both', expand=True ) scrollbar = tk.Scrollbar(frame) scrollbar.pack(side='right', fill='y') text['yscrollcommand'] = scrollbar.set scrollbar['command'] = text.yview old_stdout = sys.stdout sys.stdout = Redirect(text) root.mainloop() sys.stdout = old_stdout
- 鼠标点击Frame边缘(10像素范围内)拖动即可调整大小
- 可修改
resize_border调整可拖动区域宽度,修改最小尺寸限制值适配需求
内容的提问来源于stack exchange,提问作者kyazgan
相关产品推荐
相关产品推荐

