Reputation: 19
When your widget (in my case this label) has too long of text then how can you make it so it doesn't get cut off, depending on the the size of the root window (the main window)? I know that you can use wraplength=
attribute to wrap the text if it gets to long, although this only works if you know the length of the window before hand. So, what would you do if the user resizes the window, I know how to dynamically change the widget sizes if the window size changes, but not the text inside that widget.
Example of text getting cut off without using
wraplength=
.
Example of text using
wraplength=400
not fitting the window if the window gets resized.
As you can see from the image wraplength=
doesn't always work. Also, if was to make the window smaller then the wraplength=
then we would have the same problem of text getting cut off. So, is their a way to dynamically change the wrap length of a text depending on how wide the user has the window?
Upvotes: 0
Views: 1213
Reputation: 1858
You have to set wraplength
value to the width of the label (you can use .winfo_width()
method to get it. You would also need to update the wraplength
every time the window is being resized (the "<Configure>"
event).
So, you should do something like this (a bit simplified version):
import tkinter as tk
def enter():
label.configure(text=entry.get())
def copy_to_clipboard():
root.clipboard_append(entry.get())
def update_wraplength(_event):
label.configure(wraplength=label.winfo_width())
root = tk.Tk()
frame1 = tk.Frame(root)
entry = tk.Entry(frame1)
entry.pack(side="left", fill="x", expand=True)
tk.Button(frame1, text="Enter", command=enter)\
.pack(side="left")
frame1.pack(fill="x")
frame2 = tk.Frame(root)
label = tk.Label(frame2)
label.pack(side="left", fill="x", expand=True)
tk.Button(frame2, text="Copy to Clipoard", command=copy_to_clipboard)\
.pack(side="left")
frame2.pack(fill="x")
root.bind("<Configure>", update_wraplength)
root.mainloop()
Screenshots:
Another option is to use a Text
widget instead of a Label
. Perhaps, you will have to set its state to disabled
, as well as change some other attributes (e.g. background
or borderwidth
):
Text(root, state="disabled", ...)
Upvotes: 2