Auto truncation of a Tkinter label - python

I have a label sitting on a frame which is updated periodically to show the status of the application. Periodically, the name of the item being processed will not fit into the window, and with the way I currently have the label configured the window expands to accomidate the label.
Ideally, I'd like way to smartly truncate the text on the label (and then expand if someone expands the window). Is there an easy way to accomplish this?
Practically speaking, how can I just stop the window to expanding based on changes to text in the label?
Edit:
This is an aproximation of the code I'm working on that is not exhibiting the desired behavior (there is a link at the bottom to the actual code file):
r = tk.Tk()
statusFrame = tk.Frame(r, relief=tk.SUNKEN, borderwidth=2)
statusFrame.pack(anchor=tk.SW, fill=tk.X, side=tk.BOTTOM)
statusVar = tk.StringVar()
statusVar.set("String")
tk.Label(statusFrame, textvariable=statusVar).pack(side=tk.LEFT)
statusVar.set("this is a long text, window size should remain the same")
Actual code available here.

The answer depends very much on the way you currently have configured the widget.
For example, I can get the desired functionality as such:
>>> import Tkinter as tk
>>> r=tk.Tk()
>>> r.title('hello')
''
>>> l= tk.Label(r, name='lbl', width=20, text='reduce the window width')
>>> l.pack(fill=tk.BOTH) # or tk.X, depends; check interactive resizing now
>>> l['text']= "This is a long text, window size should remain the same"
Tell us what you do in your code for a more precise (appropriate for your code) answer.

Related

Tkinter: disable text widget content auto resize (newline), when user resize window

Advice: i'm working on Windows 8.1, with Python and Tkinter at last version; i wrote from tkinter import * to post less code here, i know that it is a bad practice, use for example import tkinter as tk instead.
I'm coding my first text editor, and i have a problem when i resize the main windows. When i run the program it display on screen a window with dimension 750x500 pixel. So far, all ok, i can write text without problem (note that menu_bar and other features are work-in progress, but we dont care about them). Problem is with Text widget when user tries to resize window with cursor. The content of the text practically adapts to the size of the window (the length of each string is reduced or increased based on the width of the window). But i don't want that this happen. I want that Text widget changes his width automatically in base of window size, but the content mustn't be adapted. I hope that you understand my question, if not, i will try to explain better.
I have searched on online reference if there's a parameter to set this option, but i haven't found anything.
How to solve the problems concerning the Text widget and resizing the window?
from tkinter import *
root = Tk()
root.geometry("750x500")
content_text = Text(root, wrap=WORD, bg="grey25", undo=True, cursor="",
insertbackground="red", foreground="white", font="courier 12")
content_text.pack(fill=BOTH, expand=True)
scroll_bar = Scrollbar(content_text)
content_text.configure(yscrollcommand=scroll_bar.set, selectbackground="dodgerblue")
scroll_bar.configure(command=content_text.yview)
scroll_bar.pack(side=RIGHT, fill=Y)
if __name__ == '__main__':
root.mainloop()
You can't do what you want. If you have wrapping turned on, text will always wrap at the edge of the window. When you change the width of the window, the text will re-wrap to the new width. There is no configuration option to tell the widget to wrap at any other place.

change size of tkinter messagebox

In python, I am attempting the change the width of the tkinter messagebox window so that text can fit on one line.
import tkinter as tk
from tkinter import messagebox
root = tk.Tk()
messagebox.showinfo("info","this information goes beyond the width of the messagebox")
root.mainloop()
It's not possible to adjust the size of messagebox.
When to use the Message Widget
The widget can be used to display short text messages, using a single font. You can often use a plain Label instead. If you need to display text in multiple fonts, use a Text widget. -effbot
Also see:
Can I adjust the size of message box created by tkMessagebox?
#CharleyPathak is correct. You either need to put a newline in the middle of the text, because message boxes can display multiple lines, or create a custom dialog box.
Heres another method that gets the effect youre looking for but doesnt use messagebox. it looks a lot longer but it just offers much more in terms of customization.
def popupmsg():
popup = tk.Tk()
def leavemini():
popup.destroy()
popup.wm_title("Coming Soon")
popup.wm_attributes('-topmost', True) # keeps popup above everything until closed.
popup.wm_attributes("-fullscreen", True) # I chose to make mine fullscreen with transparent effects.
popup.configure(background='#4a4a4a') # this is outter background colour
popup.wm_attributes("-alpha", 0.95) # level of transparency
popup.config(bd=2, relief=FLAT) # tk style
# this next label (tk.button) is the text field holding your message. i put it in a tk.button so the sizing matched the "close" button
# also want to note that my button is very big due to it being used on a touch screen application.
label = tk.Button(popup, text="""PUT MESSAGE HERE""", background="#3e3e3e", font=headerfont,
width=30, height=11, relief=FLAT, state=DISABLED, disabledforeground="#3dcc8e")
label.pack(pady=18)
close_button = tk.Button(popup, text="Close", font=headerfont, command=leavemini, width=30, height=6,
background="#4a4a4a", relief=GROOVE, activebackground="#323232", foreground="#3dcc8e",
activeforeground="#0f8954")
close_button.pack()
I managed to have a proper size for my
"tkMessageBox.showinfo(title="Help", message = str(readme))" this way:
I wanted to show a help file (readme.txt).
def helpfile(filetype):
if filetype==1:
with open("readme.txt") as f:
readme = f.read()
tkMessageBox.showinfo(title="Help", message = str(readme))
I opened the file readme.txt and EDITED IT so that the length of all lines did not exeed about 65 chars. That worked well for me. I think it is important NOT TO HAVE LONG LINES which include CR/LF in between. So format the txt file properly.

Python3/Tkinter text "displaylines" behavior issue

I am trying to count the actual lines used in a text box when it is pre-filled with data, and again when the form is submitted.
With the code below, it incorrectly shows the number of lines as chars (93) when it starts, but when you push the count button it shows the correct number of lines (4).. from the same code execution. What am I missing? (I'm new to posting on here, go easy.....)
import tkinter
text="adfa asdfkljds ;das asdjfkds fkldjasf dsf;dlsjfdkls jdkls fjd;lsfjd;ls fjd;lsafj ;dlsfj;asdlf"
def countit():
print(DE.count('1.0', 'end', 'displaylines')[0])
top = tkinter.Tk()
DE = tkinter.Text(top, height=5, width=30, wrap="word")
DE.pack()
DEButton = tkinter.Button(top, text="count", command=countit)
DEButton.pack() # WHEN BUTTON IS PRESSED, CORRECT NUMBER IS DISPLAYED
DE.insert("1.0", text)
countit() # FIRST RUN, INCORRECT NUMBER DISPLAYED
top.mainloop()
displaylines can't be calculated if the data isn't displayed, since the value depends on various factors such as the screen resolution, the actual font (which might be different than the requested font), the size of the widget once pack, place, or grid and done it's calculations, and so on. These can't be determined until the window is actually mapped to the screen.
To illustrate the point, add top.update() immediately before calling countit() and you'll see that the value is correctly printed the first time.
A better fix would be to not call countit until the window has been mapped to the screen. For example, you can add this line of code after creating the text widget:
DE.bind("<Map>", lambda event: countit())
The above will call countit() immediately after the widget has been mapped to the screen.

how to use text box in tkinter and use the values? python 3

How to create multi-lines in an entry widget in tkinter and use those inputs to create something?
For example, I want a textbox widget to come up and ask the user:
How many squares do you want? (ex: 4x4, 5x5)
What color do you want them?
And with the users input, I would like to create that many x-amount of squares in that specific height/width and specify the colors etc.
I am totally new to tkinter and I'm not really sure how to approach this.
I tried using this, but i'm not really sure how to add more lines and to use the values inputted.
import tkinter
from tkinter import *
class Squares:
root = Tk()
root.title('Random')
x = Label(text='How many squares? (ex: 4x4, 5x3)').pack(side=TOP,padx=10,pady=10)
Entry(root, width=10).pack(side=TOP,padx=10,pady=10)
Button(root, text='OK').pack(side= LEFT)
Button(root, text='CLOSE').pack(side= RIGHT)
You have a number of problems here.
I'm not sure what the Squares class is supposed to be doing, but it's basically not doing anything. You have a bunch of code that runs when you define the class, creating a few variables (which will end up as class attributes, shared by all instances of the class), and… that's it. Rather than try to figure out what you're intending here, I'm just going to scrap the class and make it all module-level code.
You never call root.mainloop(), so your program will just define a GUI and then never run it.
You don't bind your buttons to anything, so there's no way they can have any effect. You need to create some kind of function that does something, then pass it as the command argument, or .bind it later.
You don't store references for any of your controls, so there's no way to access them later. If you want to get the value out of the entry, you need some way to refer to it. (The exception is your x variable, but that's going to be None, because you're setting it to the result of calling pack on the Label, not the Label itself.)
Once you've done that, you just need to parse the value, which is pretty easy.
Putting it all together:
import tkinter
from tkinter import *
root = Tk()
root.title('Random')
Label(text='How many squares? (ex: 4x4, 5x3)').pack(side=TOP,padx=10,pady=10)
entry = Entry(root, width=10)
entry.pack(side=TOP,padx=10,pady=10)
def onok():
x, y = entry.get().split('x')
for row in range(int(y)):
for col in range(int(x)):
print((col, row))
Button(root, text='OK', command=onok).pack(side=LEFT)
Button(root, text='CLOSE').pack(side= RIGHT)
root.mainloop()
You just have to change that print to do something useful, like creating the squares.
If you don't need an outline for the text box, create_text would be the easiest thing, even though it doesn't have a wrap text feature(at least, in python 3 you can do this):
from tkinter import *
tk = Tk()
canvas = Canvas(tk, 1000, 1000)
canvas.pack()
canvas.create_text(200, 200, text="Example Text")
Try it!

Create resizable/multiline Tkinter/ttk Labels with word wrap

Is it possible to create a multi-line label with word wrap that resizes in sync with the width of its parent? In other words the wordwrap behavior of Notepad as you change the width of the NotePad window.
The use case is a dialog that needs to present a block of multi-line text (instructions) in its entirety without having the text clipped or resorting to scrollbars. The parent container will have enough vertical space to accomodate narrow widths.
I've been experimenting with Tkinter Label and Message widgets and the ttk Label widget without success. It seems that I need to hard code a pixel wraplength value vs. have these controls auto wordwrap when their text reaches the right edge of their containers. Certainly Tkinters geometry managers can help me auto-resize my labels and update their wraplength values accordingly?
Should I be looking at the Text widget instead? If so, is it possible to hide the border of a Text widget so I can use it as a multi-line label with wordwrap?
Here's a prototype of how one might do what I described above. It was inspired by Bryan Oakley's tip to use the Text widget and the following post on Stackoverflow:
In python's tkinter, how can I make a Label such that you can select the text with the mouse?
from Tkinter import *
master = Tk()
text = """
If tkinter is 8.5 or above you'll want the selection background to appear like it does when the widget is activated. Comment this out for older versions of Tkinter.
This is even more text.
The final line of our auto-wrapping label that supports clipboard copy.
""".strip()
frameLabel = Frame( master, padx=20, pady=20 )
frameLabel.pack()
w = Text( frameLabel, wrap='word', font='Arial 12 italic' )
w.insert( 1.0, text )
w.pack()
# - have selection background appear like it does when the widget is activated (Tkinter 8.5+)
# - have label background color match its parent background color via .cget('bg')
# - set relief='flat' to hide Text control borders
# - set state='disabled' to block changes to text (while still allowing selection/clipboard copy)
w.configure( bg=master.cget('bg'), relief='flat', state='disabled' )
mainloop()
Use Message widget:
The Message widget is a variant of the Label, designed to display multiline messages. The message widget can wrap text, and adjust its width to maintain a given aspect ratio.
No, there is no feature built-in to Tk to auto-word-wrap labels. However, it's doable by binding to the <Configure> event of the label and adjusting the wrap length then. This binding will fire every time the label widget is resized.
The other option, as you suggest, is to use a text widget. It is possible to entirely turn off the border if you so desire. This has always been my choice when I want word-wrapped instructional text.
Here is the code:
entry = Label(self, text=text,
anchor=NW, justify=LEFT,
relief=RIDGE, bd=2)
def y(event, entry=entry):
# FIXME: make this a global method, to prevent function object creation
# for every label.
pad = 0
pad += int(str(entry['bd']))
pad += int(str(entry['padx']))
pad *= 2
entry.configure(wraplength = event.width - pad)
entry.bind("<Configure>", y )
The tkinter.Message widget suggested by some people does NOT use TTK styling, which means that it's gonna look like garbage inside a TTK (themed) interface.
You could manually apply the background and foreground colors from your TTK theme to the tkinter.Message (by instantiating ttk.Style() and requesting the active themes' TLabel foreground and background colors from that style object), but it's not worth it... because the ancient Message widget has ZERO advantages over TTK's regular ttk.Label.
The tkinter.Message widget has an "aspect ratio" property that defines how many pixels until it wraps.
The ttk.Label instead has a wraplength= property which determines how many pixels until the words wrap. You should also use its anchor= and justify= properties to customize it to your exact desires. With these properties you can make your Label behave as the old Message widget did.
Example: ttk.Label(root, text="foo", wraplength=220, anchor=tkinter.NW, justify=tkinter.LEFT). Creates a beautifully styled label which permanently wraps its text after 220 pixels wide.
As for automatically updating the wraplength? Well, you should attach to the <Configure> event as people have said... However, if you have a completely fluid window (which resizes itself to fit all content), or a grid/frame that is fluid and contains the label, then you can't automatically calculate it that way, because the parent WINDOW/CONTAINER itself will EXPAND whenever the label grows too wide. Which means that the label will always resize itself to the maximum width it would need to fit all text. So, updating wraplength automatically is only possible if the label itself has some constraints on how wide it can grow (either via its parent container being a fixed size/maxsize, or itself being a fixed size/maxsize). In that case, sure, you can use configure to calculate new wrapping numbers to make sure the text always wraps... However, the example code by t7ko is broken and not valid anymore, just fyi.

Categories