When the following code is run, a text box appear with scrollable. However, I need to make the textbox resizable with the cursor. How can I it?
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 = tk.Frame(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
CodePudding user response:
Change this:
frame.place(x=650, y=310, anchor="c", width=850, height=400 )
to:
frame.pack(side='left', fill='both', expand=True)
CodePudding user response:
Tkinter doesn't directly support this. However, it includes all of the basic building blocks to accomplish this.
All you need to do is add a resize grip that the user can click on, and then bindings to resize the widget when you click and drag that grip.
Here's a simple example. It uses the ttk Sizegrip
widget. That widget has built-in bindings to resize the window, but we can override them with custom bindings to resize the widget instead. This example requires that you use place, since that's what your original example uses.
import tkinter as tk
from tkinter import ttk
class ResizableText(tk.Frame):
def __init__(self, parent, **kwargs):
super().__init__(parent)
self.text = tk.Text(self, **kwargs)
self.scrollbar = tk.Scrollbar(self, command=self.text.yview)
self.scrollbar.pack(side="right", fill="y")
self.text.pack(side="left", fill="both", expand=True)
sizegrip = ttk.Sizegrip(self.text)
sizegrip.place(relx=1.0, rely=1.0, anchor="se")
sizegrip.configure(cursor="sizing")
sizegrip.bind("<1>", self._resize_start)
sizegrip.bind("<B1-Motion>", self._resize)
def _resize_start(self, event):
self._x = event.x
self._y = event.y
return "break"
def _resize(self, event):
delta_x = event.x - self._x
delta_y = event.y - self._y
self.place_configure(
width = self.winfo_width() delta_x,
height = self.winfo_height() delta_y
)
return "break"
root = tk.Tk()
root.geometry("1200x620 1 1")
rt = ResizableText(root, width=25, height=8, wrap="word")
rt.place(x=650, y=310, anchor="c", width=850, height=400 )
root.mainloop()