tkinter resize label width (grid_propagate not working) - python-3.x

I'm having problem with adjusting the width of the label to reflect current width of the window. When the window size changes I'd like label to fill the rest of the width that is left after other widgets in row consume width they need.
Putting the label in a Frame and using grid_propagate(False) does not seem to work.
Consider following code:
import tkinter as tk
import tkinter.ttk as ttk
class PixelLabel(ttk.Frame):
def __init__(self,master, w, h=20, *args, **kwargs):
'''
creates label inside frame,
then frame is set NOT to adjust to child(label) size
and the label keeps extending inside frame to fill it all,
whatever long text inside it is
'''
ttk.Frame.__init__(self, master, width=w, height=h,borderwidth=1)
#self.config(highlightbackground="blue")
self.grid_propagate(False) # don't shrink
self.label = ttk.Label(*args, **kwargs)
self.label.grid(sticky='nswe')
def resize(self,parent,*other_lenghts):
'''
resizes label to take rest of the width from parent
that other childs are not using
'''
parent.update()
new_width = parent.winfo_width()
print(new_width)
for lenght in other_lenghts:
new_width -= lenght
print(new_width)
self.configure(width = new_width)
root = tk.Tk()
master = ttk.Frame(root)
master.grid()
label = ttk.Label(master,text='aaa',borderwidth=1, relief='sunken')
label.grid(row=0,column=0)
label1_width = 7
label1 = ttk.Label(master,text='bbbb',borderwidth=1, relief='sunken',width=label1_width)
label1.grid(row=0,column=1)
label2 = ttk.Label(master,text='ccccccccccccccccccccccccccccccccccccc',borderwidth=1, relief='sunken')
label2.grid(row=0,column=2)
label3_width = 9
label2 = ttk.Label(master,text='ddddd',borderwidth=1, relief='sunken',width=label2_width)
label2.grid(row=0,column=3)
label4 = ttk.Label(master,text='ee',borderwidth=1, relief='sunken')
label4.grid(row=1,column=0)
label5 = ttk.Label(master,text='f',borderwidth=1, relief='sunken')
label5.grid(row=1,column=1,sticky='we')
nest_frame = ttk.Frame(master)
nest_frame.grid(row=2,columnspan=4)
label8_width = 9
label8 = ttk.Label(nest_frame,text='xxxxx',borderwidth=1, relief='sunken',width=label8_width)
label8.grid(row=0,column=0)
label9 = PixelLabel(nest_frame, 5, text='should be next to xxxxx but is not?',borderwidth=1, relief='sunken')
label9.grid(row=0,column=1)
label9.resize(root,label2_width)
root.mainloop()
Why label9 does not appear next to label8
How to make label9 resize to meet current window size (this code is just a sample, I would like to be able to resize label9 as the window size changes dynamically when functions are reshaping the window)

It's not clear why you are using a label in a frame. I suspect this is an XY problem. You can get labels to consume extra space without resorting to putting labels inside frames. However, since you posted some very specific code with very specific questions, that's what I'll address.
Why label9 does not appear next to label8
Because you are creating the label as a child of the root window rather than a child of the frame. You need to create the label as a child of self inside PixelLabel:
class PixelLabel(...):
def __init__(...):
...
self.label = ttk.Label(self, ...)
...
How to make label9 resize to meet current window size (this code is just a sample, I would like to be able to resize label9 as the window size changes dynamically when functions are reshaping the window)
There are a couple more problems. First, you need to give column zero of the frame inside PixelFrame a non-zero weight so that it uses all available space (or, switch to pack).
class PixelLabel(...):
def __init__(...):
...
self.grid_columnconfigure(0, weight=1)
...
Second, you need to use the sticky attribute when placing nest_frame in the window so that it expands to fill its space:
nest_frame.grid(..., sticky="ew")

Related

ttk, How to position heading inside Labelframe instead of on the border?

I am trying to create an own ttk Theme based on my company's CI. I took the Sun Valley theme as starting point and swapped out graphics, fonts and colors.
However I am stuck on the Label frame. I am trying to position the Label within the frame, kind of like a heading. I.e. there should be some margin between top edge and label, and appropriate top-padding for the content (child widgets).
Now:
+-- Label ------
| ...
Desired:
+---------------
| Label
| ...
I tried to set the padding option:
within the Layout
on TLabelframe itself
on TLabelframe.Label
but the label did not move a pixel. How to achieve this?
Generally I am very confused about what identifiers and options are legal within ttk:style layout, ttk:style element and ttk:style configure, because documentation is hazy and scattered all over the 'net, and there are no error messages whatsoever. Any helpful tips?
Edit: What I found out since posting:
The Labelframe label is a separate widget altogether, with the class TLabelframe.Label.
It is possible to override its layout and add a spacer on top, shifting the text down.
However, the label widget is v-centered on the frame line. If its height increases, it pushes "upward" as much as downward. I found no way to alter the alignment w.r.t. to the actual frame.
It might be possible to replace Labelframe altogether with a custom Frame subclass with the desired layout. But that means changing the "client" code in many places. :-/
This can be done by changing the layout definitions so that the text element is held by the Labelframe layout and the Layoutframe.Label no longer draws the text element. Adding a bit of padding ensures the contained widgets leave the label clear.
Example code:
import sys
import tkinter as tk
import tkinter.ttk as ttk
class CustomLabelframe(ttk.Labelframe):
def __init__(self, master, **kwargs):
"""Initialize the widget with the custom style."""
kwargs["style"] = "Custom.Labelframe"
super(CustomLabelframe, self).__init__(master, **kwargs)
#staticmethod
def register(master):
style = ttk.Style(master)
layout = CustomLabelframe.modify_layout(style.layout("TLabelframe"), "Custom")
style.layout('Custom.Labelframe.Label', [
('Custom.Label.fill', {'sticky': 'nswe'})])
style.layout('Custom.Labelframe', [
('Custom.Labelframe.border', {'sticky': 'nswe', 'children': [
('Custom.Labelframe.text', {'side': 'top'}),
('Custom.Labelframe.padding', {'side': 'top', 'expand': True})
]})
])
if (style.configure('TLabelframe')):
style.configure("Custom.Labelframe", **style.configure("TLabelframe"))
# Add space to the top to prevent child widgets overwriting the label.
style.configure("Custom.Labelframe", padding=(0,12,0,0))
style.map("Custom.Labelframe", **style.map("TLabelframe"))
master.bind("<<ThemeChanged>>", lambda ev: CustomLabelframe.register(ev.widget))
#staticmethod
def modify_layout(layout, prefix):
"""Copy a style layout and rename the elements with a prefix."""
result = []
for item in layout:
element,desc = item
if "children" in desc:
desc["children"] = HistoryCombobox.modify_layout(desc["children"], prefix)
result.append((f"{prefix}.{element}",desc))
return result
class App(ttk.Frame):
"""Test application for the custom widget."""
def __init__(self, master, **kwargs):
super(App, self).__init__(master, **kwargs)
self.master.wm_geometry("640x480")
frame = self.create_themesframe()
frame.pack(side=tk.TOP, fill=tk.BOTH)
for count in range(3):
frame = CustomLabelframe(self, text=f"Frame {count}", width=160, height=80)
frame.pack(side=tk.TOP, expand=True, fill=tk.BOTH)
button = ttk.Button(frame, text="Test")
button.pack(side=tk.LEFT)
self.pack(side=tk.TOP, expand=True, fill=tk.BOTH)
def create_themesframe(self):
frame = ttk.Frame(self)
label = ttk.Label(frame, text="Theme: ")
themes = ttk.Combobox(frame, values=style.theme_names(), state="readonly")
themes.current(themes.cget("values").index(style.theme_use()))
themes.bind("<<ComboboxSelected>>", lambda ev: style.theme_use(ev.widget.get()))
label.pack(side=tk.LEFT)
themes.pack(side=tk.LEFT)
return frame
def main(args=None):
global root, app, style
root = tk.Tk()
style = ttk.Style(root)
CustomLabelframe.register(root)
app = App(root)
try:
import idlelib.pyshell
sys.argv = [sys.argv[0], "-n"]
root.bind("<Control-i>", lambda ev: idlelib.pyshell.main())
except Exception as e:
print(e)
root.mainloop()
return 0
if __name__ == '__main__':
sys.exit(main(sys.argv[1:]))
It is relatively easy to place ttk.Labelframe text below, on or above the relief graphic. This example uses the text attribute but labelwidget can also be used.
In order for the relief to be visible the background color of Labelframe.Label must be set to "".
import tkinter as tk
from tkinter import font
from tkinter import ttk
message = "Hello World"
master = tk.Tk()
style = ttk.Style(master)
style.theme_use(themename = "default")
actualFont = font.Font(
family = "Courier New", size = 20, weight = "bold")
style.configure(
"TLabelframe.Label", background = "", font = actualFont)
frame = ttk.LabelFrame(
master, labelanchor = "n", text = message)
frame.grid(sticky = tk.NSEW)
frame.rowconfigure(0, weight = 1)
frame.columnconfigure(0, weight = 1)
def change_heading():
if frame["text"][0] == "\n":
frame["text"] = f"{message}\n"
else:
frame["text"] = f"\n{message}"
button = tk.Button(
frame, text = "Change", command = change_heading)
button.grid(sticky = "nsew")
master.mainloop()
Looking through the source of the Labelframe widget, I found that:
The label is either placed vertically-centered on the frame's border, or flush above it, depending on the -labeloutside config option. (for default NW anchor)
i.e. by adding whitespace on top of the text by any means, the label box will extend upwards the same amount as downwards, creating a "dead space" above the frame.
There might still be a way to get it "inside" by increasing the border width, but I couldn't get it to work.
I now used the labeloutside option to make a "tab-like" heading.
# ... (define $images array much earlier) ...
ttk::style element create Labelframe.border image $images(card2) \
-border 6 -padding 6 -sticky nsew
ttk::style configure TLabelframe -padding {8 8 8 8} -labeloutside 1 -labelmargins {2 2 2 0}
ttk::style element create Label.fill image $images(header2) -height 31 -padding {8 0 16 0} -border 1
With suitable images, this is nearly what I was aiming for, only that the header does not stretch across the full frame width. Tkinter elements use a "9-patch"-like subdivision strategy for images, so you can make stretchable frames using the -border argument for element create.
Result is approximately this:
+-------------+
| Heading |
+-------------+----------------+
| ... |

Widget in a second frame in a main class does not appear

I am trying to add a second frame inside my main class and put there a few widgets. I created a frame by using a method and assigned one of the widget to that frame but the problem is it does not appear.
I provided below piece of code with window configuration and 2x Labels which are at the main frame (Both appear correctly) and one in the new frame which appearing problem.
If you have some idea, please help me :)
import tkinter as tk
class MainApplication(tk.Tk):
def __init__(self):
super().__init__()
# Adding a background picture
self.background_img = tk.PhotoImage(file="in office.png")
back_ground_img_label = tk.Label(self, image=self.background_img)
back_ground_img_label.pack(fill="both", expand=True)
# Adjusting the window
width_of_window = 1012
height_of_window = 604
screen_width = self.winfo_screenwidth()
screen_height = self.winfo_screenheight()
x_coordinate = int((screen_width / 2) - (width_of_window / 2))
y_coordinate = int((screen_height / 2) - (height_of_window / 2) - 30)
self.geometry(
f"{width_of_window}x{height_of_window}+{x_coordinate}+{y_coordinate}"
)
self.bet_frame()
bet_value_label_bg = tk.Label(self)
bet_value_label_bg.place(x=462, y=300)
coin_button_1 = tk.Button(self.frame)
coin_button_1.place(x=233, y=435)
def bet_frame(self):
self.frame = tk.Frame(width=1012, height=604)
self.frame.pack()
if __name__ == "__main__":
MainApplication().mainloop()
The only thing you put in the self.frame is the coin_button_1, but as you place it at (233, 435) is is hidden below the main window self.
Personally I would not use place but rather either pack or even better grid to place the widgets on the screen (see Setting Frame width and height)
So if you change def bet_frame(self) as follows it will be visible
...
bet_value_label_bg = tk.Label(self, text='value')
bet_value_label_bg.place(x=462, y=300)
def bet_frame(self):
self.frame = tk.Frame(master=self, width=1012, height=604)
self.frame.pack()
coin_button_1 = tk.Button(self.frame, text='coin button')
coin_button_1.pack()
...
Note the bet_value_label_bg shows up in the middle of the picture and you may have to expand the main window to make the self.frame visible, depending on the size of the picture.

How to enhance window size selection on a tkinter project including button-image as label?

I'm currently working on a little project on python-3.x including some tkinter ressources. My program is made to display on a screen a list of pictures included in a directory, each picture is put on a button that is a sixth of the original image, and if we click on it, it display the image on his original size on a new window. The original window is set by the amount of pictures i put in the columns (i can choose in the code) and i ve made a scrollbar because i have to work with a lot of pictures.
But here is my problem, it's works fine except that if i change the window size, like reduce it for example, the buttons don't follow, they just vanish behind the window, and with the scrollbar.
I'm not particularly good in python so i was wondering that maybe by doing like a threading we could get the window size in live and then if the window size is inferior/superior of our columns of buttons, we could resize it and change the amount of columns then reload the page, but i will have to work with multiple image so it will take a lot of time.
from tkinter import *
from tkinter.filedialog import *
from tkinter.messagebox import *
from PIL import Image, ImageTk
import tkinter as tk
import glob
import os
import cv2
import copy
import _thread
import time
folder = 'X:/users/Robin/data/dataset-valid/visu/*.jpg'
a=glob.glob(folder)
fic = "../data/list.txt"
fichObj=open(fic,"w")
p = []
for f in a:
fichObj.write(f+"\n")
fichObj.close()
class SuperPhoto(object):
def __init__(self, photo , image):
self.photo = photo
temp = cv2.resize(image, (int((self.photo.width())/6) , int((self.photo.height())/6)))
red = temp[:,:,2].copy()
blue = temp[:,:,0].copy()
temp[:,:,0] = red
temp[:,:,2] = blue
temp = Image.fromarray(temp)
self.miniature = ImageTk.PhotoImage(temp)
def agrandir(self):
Newfen=Toplevel()
Newfen.geometry("+60+60")
#self.photo.resize((500,500))
print(type(self.photo))
label = Label(Newfen, image=self.photo, width=self.photo.width(), height=self.photo.height())
label.image = self.photo # keep a reference!
label.pack()
if os.path.exists (fic): #os.path utile
count = len(open(fic).readlines())
print(count)
#lin = open(fic).readlines()
#print(lin)
class ScrollableCanvas(Frame):
def __init__(self, parent, *args, **kw):
Frame.__init__(self, parent, *args, **kw)
canvas=Canvas(self,bg='#FFFFFF',width=300,height=300,scrollregion=(0,0,500,500))
canvas.update_idletasks()
vbar=Scrollbar(self,orient=VERTICAL)
vbar.pack(side=RIGHT, fill=Y)
vbar.config(command=canvas.yview)
canvas.config(width=1200,height=700)
canvas.config(yscrollcommand=vbar.set)
canvas.pack(side=LEFT,expand=True,fill=BOTH)
# create a frame inside the canvas which will be scrolled with it
self.interior = interior = Frame(canvas)
interior_id = canvas.create_window(0, 0, window=interior, anchor=NW )
# track changes to the canvas and frame width and sync them,
# also updating the scrollbar
def _configure_interior(event):
# update the scrollbars to match the size of the inner frame
size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
canvas.config(scrollregion="0 0 %s %s" % size)
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the canvas's width to fit the inner frame
canvas.config(width=interior.winfo_reqwidth())
interior.bind('<Configure>', _configure_interior)
def _configure_canvas(event):
if interior.winfo_reqwidth() != canvas.winfo_width():
# update the inner frame's width to fill the canvas
canvas.itemconfigure(interior_id, width=canvas.winfo_width())
canvas.bind('<Configure>', _configure_canvas)
class Main_frame(Frame):
# Init
def __init__(self, fenetre_principale=None):
Frame.__init__(self, fenetre_principale)
self.grid()
self.scrollable_canvas = ScrollableCanvas(self)
self.scrollable_canvas.grid(row=1,column=1)
nbCol = 4
for file in a:
image = Image.open(file)
photo = ImageTk.PhotoImage(image)
w = photo.width()
L.append(int(w/6))
#print(L)
sumL = int(sum(L)/nbCol)
print(sumL)
p.append(SuperPhoto(photo, cv2.imread(file)))
for ligne in range(int(count/nbCol)):
for colonne in range(nbCol):
photo = p[ligne * nbCol + colonne]
button = Button(self.scrollable_canvas.interior, image=photo.miniature, command=photo.agrandir)
button.grid(row=ligne, column=colonne)
if __name__ == "__main__":
root = Tk()
root.title("VISU")
root.geometry("+0+0")
L= []
interface = Main_frame(fenetre_principale=root)
root.update_idletasks()
print(root.winfo_width())
print(root.geometry())
interface.mainloop()
So, I except this program to work like a classic directory display, with the columns that change automatically when we resize the window and with the scrollbar that follow it.
If you have any solutions it will really help me ..
You can try it, just put some jpeg pictures in a directory and change the folder variable with the link of your directory.
Thanks in advance for your help, if you have any questions to understand more clearly what i've said don't hesitate.
Each time the root window is resized, a <Configure> event is triggered. Catch it as follows:
def resize(event):
root.update_idletasks()
#update all image sizes here if needed
#all widgets can be 're-grided' here based on new width and height of root window
root.bind('<Configure>', resize)
If you want to ensure that your window cannot be resized, use the following:
root.resizable(False, False)

Print Result to Canvas Not to the shell window

Attached is part of a GUI i have constructed in Tkinter using a canvas, hence makes it possible to insert an image in the background.
When I call the function Relay_1: the result is sent to the Python shell window.
What i would like is a text box in the canvas, and show the result (i.e print the result) on the canvas and not in the shell.
Any ideas would be appreciated.
import Tkinter
#Function
def Relay_1():
arduinoData.write(b'1')
print ("This is a test\n")
class ProgramGUI:
def __init__(self):
# Creates the Main window for the program
self.main = tkinter.Tk()
# Change Default ICON
self.main.iconbitmap(self,default = 'test.ico')
# Create title, window size and make it a non re sizable window
self.main.title('Test')
self.main.resizable(False, False)
self.main.geometry('680x300')
self.canvas = tkinter.Canvas(self.main, width = 680, height = 300)
self.canvas.pack()
self.logo = tkinter.PhotoImage(file = 'test.png')
self.canvas.create_image(0,0,image = self.logo, anchor = 'nw')
# Create 3 Frame to group the widgets
self.top = tkinter.Frame(self.main)
self.middle = tkinter.Frame(self.main)
self.bottom = tkinter.Frame(self.main)
etc etc
The tkinter canvas widget has a very simple and easy to use method to draw text called create_text(). You can use it this way,
self.canvas.create_text(10, 10, text='This is a test\n')
The text can be customized by passing a wide range of arguments including font,fill and justify. Check the full list of passable arguments here:http://effbot.org/tkinterbook/canvas.htm#Tkinter.Canvas.create_text-method
To add the text when the code is executed, you could create a class inside ProgramGUI() method:
def draw_text(self, text):
self.canvas.create_text(10, 10, text=text)
And use it after creating an object.

How do I size QLayout based on proportionality?

I'm creating a simple dialog box for my PySide application. Within this dialog, there are going to be multiple inputs that the user will have to fill out. Associated with those inputs are labels that go alongside the left of the labels. Right now I create the label, input pair using a separate class:
class inputLayout(PyGui.QHBoxLayout):
def __init__(self, Label, parent):
super(inputLayout, self).__init__()
label = PyGui.QLabel()
label.setText(Label)
self.addWidget(label)
self.__input = PyGui.QTextEdit()
self.addWidget(self.__input)
parent.addLayout(self)
and then add it to the master layout like so:
layout = PyGui.QVBoxLayout()
self.amp = inputLayout('Amplitude', layout)
self.test = inputLayout('test', layout)
self.test2 = inputLayout('test2', layout)
The problem is that when PySide does its automagic, it get something like the following:
Like my image suggests, I'd rather have the Label take up 1/3 (or some other proportional rate of my choice) to make it look more unified. How do I size the layout using this proportionality, or ratio?
I am aware of this question, however I'm not looking to statically set the size of the label, but rather do it dynamically using a ratio.
Here's a small example that should solve your problem. The key is in two parts:
Use a QGridLayout, which sets the column width to the width of the widest widget in its column (unless defined otherwise). This ensures that everything is aligned nicely along the vertical axis.
Set a stretch factor. This determines how an element should resize when their parent is resized. By default it's 0, so you don't have to set it, I just added it for illustration purposes. By setting the text_edit's column to 1, it will start stretching. By playing with the factors, you can make one column grow faster than the other.
from PySide import QtGui
import sys
class MainWindow(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
self.input_widget = InputWidget(self)
self.layout = QtGui.QVBoxLayout()
self.layout.addWidget(self.input_widget)
self.setLayout(self.layout)
self.setCentralWidget(self.input_widget)
class InputWidget(QtGui.QWidget):
def __init__(self, parent):
super(InputWidget, self).__init__(parent)
self.grid_layout = QtGui.QGridLayout()
self.labels = ["amp", "more text", "blabla"]
self.text_edits = []
self.qlabels = []
for row, label in enumerate(self.labels):
label = QtGui.QLabel(label)
self.qlabels.append(label)
self.grid_layout.addWidget(label, row, 0)
text_edit = QtGui.QTextEdit()
self.text_edits.append(text_edit)
self.grid_layout.addWidget(text_edit, row, 1)
self.grid_layout.setColumnStretch(0, 0)
self.grid_layout.setColumnStretch(1, 2)
self.setLayout(self.grid_layout)
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
window = MainWindow()
window.show()
app.exec_()
If you want to access the text from the text_edit, you could search for the label's index in self.labels and then use that label in self.text_edits to retrieve the corresponding text_edit. Alternatively, once you close the dialog, you could loop through both self.labels and self.text_edits and create a dictionary that maps the label to the text from the text_edit.
results = {}
for label, text_edit in zip(self.labels, self.text_edits):
results[label] = text_edit.text()

Resources