Reputation: 23
I am having issues with the below code. I saw this code on a udemy course done by a instructor, and he defined small partitions in a tkinter window using .pack()
method.
The issue is that I need to use .grid()
later down the line, and since both methods can't be used in the same program, I need to convert the .pack()
to .grid()
, but I have no idea how to do that. How would it be done?
from tkinter import *
import time
from tkinter import ttk
#~~~~~~~~~~~~~~Defining the window~~~~~~~~~~~~~
root=Tk()
root.title("Parent window")
root.geometry('1600x800+0+0')
root.configure(bg='#FFFFFF')
#~~~~~~~~~~~~~~window~partition~~~~~~~~~~~~~~~~
top=Frame(root, width=1600, height=100, bg='blue', relief=SUNKEN)
top.pack(side=TOP) #i need to change this .pack() to something else to make the program compatible with .grid() for all the lines
w1=Frame(root, width=800, height=700, bg='purple', relief=SUNKEN)
w1.pack(side=LEFT)
w2=Frame(root, width=300, height=700, bg='green', relief=SUNKEN)
w2.pack(side=RIGHT)
w3=Frame(root, width=35, height=700, bg='orange', relief=SUNKEN)
w3.pack(side=LEFT)
w4=Frame(root, width=100, height=700, bg='pink', relief=SUNKEN)
w4.pack(side=LEFT)
root.mainloop()
Upvotes: 2
Views: 371
Reputation: 3285
You can use both pack
and grid
within the same tkinter program. Just as long as you don't mix methods that has the same parent widget.
You can see an example below with a program that mixes pack
and grid
:
from tkinter import *
import time
from tkinter import ttk
#~~~~~~~~~~~~~~Defining the window~~~~~~~~~~~~~
root=Tk()
root.title("Parent window")
root.geometry('1600x800+0+0')
root.configure(bg='#FFFFFF')
#~~~~~~~~~~~~~~window~partition~~~~~~~~~~~~~~~~
top=Frame(root, width=1600, height=100, bg='blue', relief=SUNKEN)
top.pack(side=TOP)
# Here I create a new parent frame, to contain the widgets we wish to
# use .grid() for instead of .pack()
gridframe = Frame(root, width=1600, height=700)
gridframe.pack(side=TOP)
w1=Frame(gridframe, width=800, height=700, bg='purple', relief=SUNKEN)
w1.grid(row=0, column=0)
w2=Frame(gridframe, width=300, height=700, bg='green', relief=SUNKEN)
w2.grid(row=0, column=1)
w3=Frame(gridframe, width=35, height=700, bg='orange', relief=SUNKEN)
w3.grid(row=0, column=2)
w4=Frame(gridframe, width=100, height=700, bg='pink', relief=SUNKEN)
w4.grid(row=0, column=3)
root.mainloop()
To replicate the result you got with the pack
function, please try something like the following. I am using padx
to add the whitespace between the widgets so it matches what you saw when packing
w1=Frame(gridframe, width=800, height=700, bg='purple', relief=SUNKEN)
w1.grid(row=0, column=0)
w2=Frame(gridframe, width=35, height=700, bg='orange', relief=SUNKEN)
w2.grid(row=0, column=1)
w3=Frame(gridframe, width=100, height=700, bg='pink', relief=SUNKEN)
w3.grid(row=0, column=2)
w4=Frame(gridframe, width=300, height=700, bg='green', relief=SUNKEN)
w4.grid(row=0, column=3, padx=1600-800-35-100-300)
Upvotes: 3