I need a specific layout for the gui I'm making with Tkinter/ttk on python 2.7, that's why I want to use the grid positioner to master my ttk widgets' relative positions. But everytime I run my code, nothing appears.
ps: I used some widgets with grid(), and some others with pack()
I don't know where's the problem! Here's the code:
from Tkinter import *
import ttk
master = Tk()
f4=Frame(master,width=300,height=300,bg="powder blue",relief=SUNKEN)
f4.pack(side=BOTTOM,fill=BOTH, expand=True)
test = True
f3=Frame(master,width=300,height=300,bg="red",relief=SUNKEN)
f3.pack(side=TOP,fill=BOTH, expand=True)
def create():
global test
if test:
global e
e = ttk.Entry(f4).grid(row=2,column=0, columnspan=2)
test = False
#e.focus_set()
def callback():
print e.get()
b = Button(master, text="get", width=10, command=callback)
b.grid(row=0, column=0)
c = Button(master, text="set", width=10, command=callback)
c.grid(row=0, column=1)
create()
mainloop()
Your problem is the use of pack()
and grid()
at the same time on the master
window.
Use one or the other per container.
A container is the main root
window, a Toplevel()
window or a Frame
.
Try something like this without pack()
:
from Tkinter import *
import ttk
master = Tk()
master.rowconfigure(0, weight=1)
master.columnconfigure(0, weight=1)
master.columnconfigure(1, weight=1)
f3=Frame(master,width=300,height=300,bg="red",relief=SUNKEN)
f3.grid(row=0, column=0, columnspan=2, sticky="nsew")
f4=Frame(master, width=300, height=300, bg="powder blue", relief=SUNKEN)
f4.grid(row=1, column=0, columnspan=2, sticky="nsew")
test = True
def create():
global test
if test:
global e
e = ttk.Entry(f4).grid(row=2,column=0, columnspan=2)
test = False
def callback():
print e.get()
b = Button(master, text="get", width=10, command=callback)
b.grid(row=2, column=0, sticky="e")
c = Button(master, text="set", width=10, command=callback)
c.grid(row=2, column=1, sticky="w")
create()
master.mainloop()
Here is a version just using pack()
.
I changed it up a little to give a different layout that might be closer to what you are trying.
from Tkinter import *
import ttk
master = Tk()
f3 = Frame(master, width=300, height=300, bg="red", relief=SUNKEN)
f3.pack(side=TOP, fill=BOTH, expand=True)
f4 = Frame(master, width=300, height=300, bg="powder blue", relief=SUNKEN)
f4.pack(side=TOP, fill=BOTH)
f5 = Frame(master, width=300)
f5.pack(side=BOTTOM, fill=BOTH)
test = True
def create():
global test
if test:
global e
e = ttk.Entry(f4).pack(side=TOP,fill=BOTH)
test = False
def callback():
print e.get()
b = Button(f5, text="get", width=10, command=callback)
b.pack(side=LEFT, fill=BOTH, expand=True)
c = Button(f5, text="set", width=10, command=callback)
c.pack(side=RIGHT, fill=BOTH, expand=True)
create()
master.mainloop()