Position Tkinter grid Python - python

I was doing some tests and there is something that I don't understand with grid.
This is my code :
from tkinter import *
root = Tk()
frame = Frame(root, bg='blue',width=200,height=200)
frame.grid(column=0,row=0, sticky="news")
frame2 = Frame(root, bg='red',width=200,height=200)
frame2.grid(column=1,row=0, sticky="news")
frame3 = Frame(root, bg='green',width=200,height=200)
frame3.grid(column=2,row=0, sticky="news")
frame4 = Frame(frame, bg='yellow',width=100,height=100)
frame4.grid(column=0,row=0,sticky="news")
frame4 = Frame(frame, bg='orange',width=100,height=100)
frame4.grid(column=0,row=1,sticky="news")
root.mainloop()
I wanted to have the orange and the yellow square inside my blue box. But as you can see when you run the code the blue box disappear behind the yellow and the orange. How can I solve this problem to get :

The blue frame is shrinking to the content of its children. You can avoid that by calling grid_propagate:
frame = Frame(root, bg='blue', width=200, height=200)
frame.grid(column=0,row=0, sticky="news")
frame.grid_propagate(0)
Result:

Related

Making a tkinter horizontal scroll bar with grid python

So im having trouble making a horizontal scroll bar with grid and have been trying to mix and match different parameters and such and I've hit a rock with this tutorial
https://newbedev.com/tkinter-canvas-scrollbar-with-grid
being the first example
this is my code so far
window = tk.Tk()
window.geometry("1200x600")
frame_main = tk.Frame(window, bg="gray")
frame_main.grid(sticky='news')
# Create a frame for the canvas with non-zero row&column weights
frame_canvas = tk.Frame(frame_main)
frame_canvas.grid(row=0, column=0, pady=(5, 0), sticky='nw')
frame_canvas.grid_rowconfigure(0, weight=1)
frame_canvas.grid_columnconfigure(0, weight=1)
# Add a canvas in that frame
canvas = tk.Canvas(frame_canvas, bg="yellow")
canvas.grid(row=2, column=2, sticky="news")
# Link a scrollbar to the canvas
vsb = tk.Scrollbar(window, orient="horizontal", command=canvas.xview)
vsb.grid(row=0, column=2, sticky='we')
canvas.configure(xscrollcommand=vsb.set)
frame_canvas.config(width=first5columns_width + vsb.winfo_width(),height=first5rows_height)
canvas.config(scrollregion=canvas.bbox("all"))
col_0_head = tk.Label(window, text = " Adventures_Sherlock_Holmes.txt ", pady = 20) # pady = 20 gives some vertical
# separation between this row and the next
col_0_head.grid(row = 0, column = 0)
col_1_head = tk.Label(window, text = " Age_Innocence.txt ")
col_1_head.grid(row = 0, column = 1)
col_2_head = tk.Label(window, text = " Alice_Wonderland.txt ")
col_2_head.grid(row = 0, column = 2)
window.mainloop()
If you want to create a scroll bar in tkitner using grid option, you can simply create a scrollframe and pack the scrollbar in that frame
This is the type of code you can write:
scrollframe = Frame(root)
scrollframe.grid(...)
scrollx = Scrollbar(scrollframe, orient=HORIZONTAL)
scrollx.pack(expand=1, fill=X, side=BOTTOM)
This should ideally work if you don't want the scrollbar to fill your entire GUI Bottom X-axis. In case you are ok with it filling the entire GUI, then just pack the scrollbar in your root or Tk widget.
Thank You!
Two problems in your code.
The first is no scrollregion in canvas.
The second is wrong grid row and column values.
Here's a code snippet that solves your problem.
# Add a canvas in that frame
canvas = tk.Canvas(frame_canvas, bg="yellow", scrollregion = "0 0 2000 2000")
canvas.grid(row=2, column=2, sticky="news")
# Link a scrollbar to the canvas
vsb = tk.Scrollbar(window, orient="horizontal", command=canvas.xview)
vsb.grid(row=1, column=0, sticky='ew')
canvas.configure(xscrollcommand=vsb.set)

Center an image when resizing

Working with Tkinter, I need to center entities. When trying to center labels, it will only center it within the first row, and not the window.
I want it centered within the entire window. i.e. the middle. So far, it is only the middle of the top. is this possible?
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
root = Tk()
# New window, but text appears in the center of the center (the absolute center).
def whatsup():
popup = Tk()
popup.title("Cadillac")
frame = Frame(popup)
frame.pack()
label = ttk.Label(frame, text="Wanna ride in my Cadillac?")
label.pack()
root.title("I Love You")
# 1, 1
button = Button(root, text="Ayo girl", command=whatsup)
button.pack(side=LEFT)
# 1, 2, but to be 2, 2 soon after addition of new items.
canvas = Canvas(root, height=250, width=200)
imageOfCatherine=ImageTk.PhotoImage(Image.open('ccr_on_moon.jpg'))
canvas.create_image(-160, -100, anchor=NW, image=imageOfCatherine)
canvas.pack()
root.mainloop()
You can use grid instead of pack, with rowconfigure and columnconfigure methods like this :
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
root = Tk()
root.title("I Love You")
# New window, but text appears in the center of the center (the absolute center).
def whatsup():
popup = Tk()
popup.title("Cadillac")
frame = Frame(popup)
frame.pack()
label = ttk.Label(frame, text="Wanna ride in my Cadillac?")
label.pack()
# 1, 1
button = Button(root, text="Ayo girl", command=whatsup)
button.grid(row=0, column=0, sticky='w')
# 1, 2, but to be 2, 2 soon after addition of new items.
canvas = Canvas(root, height=250, width=200)
imageOfCatherine=ImageTk.PhotoImage(Image.open('ccr_on_moon.jpg'))
canvas.create_image(-160, -100, anchor=NW, image=imageOfCatherine)
canvas.grid(row=1, column=1)
root.rowconfigure([0,1,2], weight=1)
root.columnconfigure([0,1,2], weight=1)
root.mainloop()
Answer to comment
This also works, but it's not centered the same way :
from tkinter import *
from tkinter import ttk
from PIL import ImageTk, Image
root = Tk()
root.title("I Love You")
# New window, but text appears in the center of the center (the absolute center).
def whatsup():
popup = Tk()
popup.title("Cadillac")
frame = Frame(popup)
frame.pack()
label = ttk.Label(frame, text="Wanna ride in my Cadillac?")
label.pack()
# 1, 1
button = Button(root, text="Ayo girl", command=whatsup)
button.grid(row=0, column=0, sticky='w')
# 1, 2, but to be 2, 2 soon after addition of new items.
canvas = Canvas(root, height=250, width=200)
imageOfCatherine=ImageTk.PhotoImage(Image.open('ccr_on_moon.jpg'))
canvas.create_image(-160, -100, anchor=NW, image=imageOfCatherine)
canvas.grid(row=0, column=1, sticky='')
root.rowconfigure(0, weight=1)
root.columnconfigure([0,1], weight=1)
root.mainloop()
After some tinkering (no pun intended), I added expand=YES to frame.pack() in the whatsup() function.
def whatsup():
popup = Tk()
popup.title("Cadillac")
frame = Frame(popup)
frame.pack(expand=YES) # This was the changed line!
label = ttk.Label(frame, text="Wanna ride in my Cadillac?")
label.pack()
This allows for the popup text to become centered.

Spinbox getting vanished when i go to other frame and come back to the same

I have created a spinbox on frame1 and going to frame2 by clicking NEXT, From frame2 going back to frame 1 by clicking BACK button. By the time spinbox widget getting disappear. what could be the reason?
from Tkinter import *
def swap_frame(frame):
frame.tkraise()
root = Tk()
root.geometry("900x650+220+20")
root.title("Testing")
root.configure(borderwidth="1", relief="sunken",cursor="arrow",background="#BCC3B9",highlightcolor="black")
root.resizable(width=False, height=False)
frame2 = Frame(root, width=900, height=650)
frame1 = Frame(root, width=900, height=650)
#item 1 spinbox
Platform = Spinbox(values=("SX-16F", "SX-12VP", "SX-16VP", "VSRM-A", "NRNT-A", "FX-8", "DX-48V"), width="32")
Platform.place(x=500, y=200, relheight=0.05)
Button1=Button(frame1, text="Next", width =10, height= 2, bg= "#dbd8d7", command=lambda:swap_frame(frame2))
Button1.place(x=580, y=580)
Button3=Button(frame2, text="Back", width =10, height= 2, bg= "#dbd8d7", command=lambda:swap_frame(frame1))
Button3.place(x=580, y=580)
frame2.grid(row=0, column=0)
frame1.grid(row=0, column=0)
root.mainloop()
Pass the master to your Spinbox widget. It currently defaults to Tk window which is only initially lifted, hence it gets blocked by both frames when either one is lifted. Replace:
Platform = Spinbox(values=(...), ...)
with:
Platform = Spinbox(frame1, values=(...), ...)

Frame swapping is not working

I want to switch the frame, but not able to do it
1st Page(frame) should have red background color and "Hello" button and Frame size should have 900x650 as window size. When press "Hello" button it should swap to 2nd frame
2nd page (frame) should have green background color and "Hello" button and Frame size should have 900x650 as window size. When press "Hello" button it should swap to 1st frame
import Tkinter as tk
def raise_frame(frame):
print "Inside raise frame"
frame.tkraise()
root = tk.Tk()
root.geometry("900x650+220+20")
root.title("Testing")
frame1 = tk.Frame(root, width=900, height=650, background="red")
frame2 = tk.Frame(root, width=900, height=650, background="green")
B1= tk.Button(frame1, text="Hello", width =10, height=2, command = lambda:raise_frame(frame2)).place (x=200, y=200)
B2= tk.Button(frame2, text="Hello", width =10, height=2, command = lambda:raise_frame(frame1)).place (x=400, y=400)
frame1.pack( )
frame2.pack( )
root.mainloop()
Since you are using pack(), the second frame is placed below the first frame. You can check that by dragging the bottom part of the window. You'll see that there are 2 frames created with the red on the top, and the green on the bottom.
You can use grid() to place the frames on top of each other.
So, replace the lines
frame1.pack()
frame2.pack()
with
frame1.grid(row=0, column=0)
frame2.grid(row=0, column=0)

Tkinter canvas & scrollbar with grid

I have a canvas in a frame
photoFrame = Frame(centerFrame, width=250, height=190, bg="#EBEBEB")
photoFrame.grid(row=0, column=1, sticky="nsew")
photoCanvas = Canvas(photoFrame, bg="#EBEBEB")
photoCanvas.grid(row=0, column=0, sticky="nsew")
and I try to put a scrollbar to my canvas with this
photoScroll = Scrollbar(photoFrame, orient=VERTICAL)
photoScroll.config(command=photoCanvas.yview)
photoCanvas.config(yscrollcommand=photoScroll.set)
photoScroll.grid(row=0, column=1, sticky="ns")
The scrollbar appears but it's disabled. Can you help me please ?
Sorry for my bad english.
In a for loop I add lots of Image button with this code
element = Button(photoCanvas, image = listPhotos[i], borderwidth=0, height = 200, width = 200, bg="#EBEBEB")
element.grid(row=rowPhoto, column=columnPhoto, padx=5, pady=5, sticky="nsew")
Finnally I have this
root = Tk()
photoFrame = Frame(root, width=250, height=190, bg="#EBEBEB")
photoCanvas = Canvas(photoFrame, bg="#EBEBEB")
photoCanvas.grid(row=0, column=0, sticky="nsew")
for i in range(0, len(listPhotos), 1):
element = Button(photoCanvas, image = listPhotos[i], borderwidth=0, height = 200, width = 200, bg="#EBEBEB")
element.grid(row=rowPhoto, column=columnPhoto, padx=5, pady=5, sticky="nsew")
photoScroll=Scrollbar(photoFrame,orient=VERTICAL)
photoScroll.config(command=photoCanvas.yview)
photoCanvas.config(yscrollcommand=photoScroll.set)
photoScroll.grid(row=0, column=1, sticky="ns")
in my app, the purple rectangle is the next frame and I need a vertical scrollbar
Say if you have some questions
One way to scroll a group of widgets is to put them (with grid of pack) inside a frame and put this frame inside a canvas.
The two key elements (besides connecting the scrollbar to the canvas) for the scrolling to work are:
Use canvas.create_window(x, y, window=frame) to put the frame inside the canvas so that it is treated like a canvas item.
Update the canvas scrollregion each time the size of the frame changes (for instance after adding a new widget) with canvas.configure(scrollregion=canvas.bbox('all')).
Here is an adaptation of the code of the question Python Tkinter scrollbar for frame, but using the widgets name from the OP's question and grid instead of pack:
import tkinter as tk
def update_scrollregion(event):
photoCanvas.configure(scrollregion=photoCanvas.bbox("all"))
root = tk.Tk()
photoFrame = tk.Frame(root, width=250, height=190, bg="#EBEBEB")
photoFrame.grid()
photoFrame.rowconfigure(0, weight=1)
photoFrame.columnconfigure(0, weight=1)
photoCanvas = tk.Canvas(photoFrame, bg="#EBEBEB")
photoCanvas.grid(row=0, column=0, sticky="nsew")
canvasFrame = tk.Frame(photoCanvas, bg="#EBEBEB")
photoCanvas.create_window(0, 0, window=canvasFrame, anchor='nw')
for i in range(10):
element = tk.Button(canvasFrame, text='Button %i' % i, borderwidth=0, bg="#EBEBEB")
element.grid(padx=5, pady=5, sticky="nsew")
photoScroll = tk.Scrollbar(photoFrame, orient=tk.VERTICAL)
photoScroll.config(command=photoCanvas.yview)
photoCanvas.config(yscrollcommand=photoScroll.set)
photoScroll.grid(row=0, column=1, sticky="ns")
canvasFrame.bind("<Configure>", update_scrollregion)
root.mainloop()

Categories