Python tkinter grid and pack

python pack() and grid() methods together

Im new to python so please forgive my Noob-ness. Im trying to create a status bar at the bottom of my app window, but it seems every time I use the pack() and grid() methods together in the same file, the main app window doesn’t open. When I comment out the line that says statusbar.pack(side = BOTTOM, fill = X) my app window opens up fine but if I leave it in it doesn’t, and also if I comment out any lines that use the grid method the window opens with the status bar. It seems like I can only use either pack() or grid() but not both. I know I should be able to use both methods. Any suggestions? Here’s the code:

from Tkinter import * import tkMessageBox def Quit(): answer = tkMessageBox.askokcancel('Quit', 'Are you sure?') if answer: app.destroy() app = Tk() app.geometry('700x500+400+200') app.title('Title') label_1 = Label(text = "Enter number") label_1.grid(row = 0, column = 0) text_box1 = DoubleVar() input1 = Entry(app, textvariable = text_box1) input1.grid(row = 0, column = 2) statusbar = Label(app, text = "", bd = 1, relief = SUNKEN, anchor = W) statusbar.pack(side = BOTTOM, fill = X) startButton = Button(app, text = "Start", command = StoreValues).grid(row = 9, column = 2, padx = 15, pady = 15) app.mainloop() 

im only using both because I dont know how to put the status bar on the bottom of the screen using the grid and I dont know how to fill = X with the grid function either.

Читайте также:  My webpage

3 Answers 3

You cannot use both pack and grid on widgets that have the same master. The first one will adjust the size of the widget. The other will see the change, and resize everything to fit it’s own constraints. The first will see these changes and resize everything again to fit its constraints. The other will see the changes, and so on ad infinitum. They will be stuck in an eternal struggle for supremacy.

While it is technically possible if you really, really know what you’re doing, for all intents and purposes you can’t mix them in the same container. You can mix them all you want in your app as a whole, but for a given container (typically, a frame), you can use only one to manage the direct contents of the container.

A very common technique is to divide your GUI into pieces. In your case you have a bottom statusbar, and a top «main» area. So, pack the statusbar along the bottom and create a frame that you pack above it for the main part of the GUI. Then, everything else has the main frame as its parent, and inside that frame you can use grid or pack or whatever you want.

@terencevaughn: pieces == classes? Not necessarily. While you certainly can use classes, I meant you should divide your interface into logical groups. Each group can be implemented as a frame which contains other widgets. Each logical group can be managed separately.

Yeah thats right. In following example, i have divided my program into 2 frames. frame1 caters towards menu/toolbar and uses pack() methods wherein frame2 is used to make login page credentials and uses grid() methods.

from tkinter import * def donothing(): print ('IT WORKED') root=Tk() root.title(string='LOGIN PAGE') frame1=Frame(root) frame1.pack(side=TOP,fill=X) frame2=Frame(root) frame2.pack(side=TOP, fill=X) m=Menu(frame1) root.config(menu=m) submenu=Menu(m) m.add_cascade(label='File',menu=submenu) submenu.add_command(label='New File', command=donothing) submenu.add_command(label='Open', command=donothing) submenu.add_separator() submenu.add_command(label='Exit', command=frame1.quit) editmenu=Menu(m) m.add_cascade(label='Edit', menu=editmenu) editmenu.add_command(label='Cut',command=donothing) editmenu.add_command(label='Copy',command=donothing) editmenu.add_command(label='Paste',command=donothing) editmenu.add_separator() editmenu.add_command(label='Exit', command=frame1.quit) # **** ToolBar ******* toolbar=Frame(frame1,bg='grey') toolbar.pack(side=TOP,fill=X) btn1=Button(toolbar, text='Print', command=donothing) btn2=Button(toolbar, text='Paste', command=donothing) btn3=Button(toolbar, text='Cut', command=donothing) btn4=Button(toolbar, text='Copy', command=donothing) btn1.pack(side=LEFT,padx=2) btn2.pack(side=LEFT,padx=2) btn3.pack(side=LEFT,padx=2) btn4.pack(side=LEFT,padx=2) # ***** LOGIN CREDENTIALS ****** label=Label(frame2,text='WELCOME TO MY PAGE',fg='red',bg='white') label.grid(row=3,column=1) label1=Label(frame2,text='Name') label2=Label(frame2,text='Password') label1.grid(row=4,column=0,sticky=E) label2.grid(row=5,column=0,sticky=E) entry1=Entry(frame2) entry2=Entry(frame2) entry1.grid(row=4,column=1) entry2.grid(row=5,column=1) chk=Checkbutton(frame2,text='KEEP ME LOGGED IN') chk.grid(row=6,column=1) btn=Button(frame2,text='SUBMIT') btn.grid(row=7,column=1) # **** StatusBar ****************** status= Label(root,text='Loading',bd=1,relief=SUNKEN,anchor=W) status.pack(side=BOTTOM, fill=X) 

Источник

Читайте также:  Python xlsxwriter read file

How To Position Widgets in Tkinter

How To Position Widgets in Tkinter QR Cover

Before we start: This Python tutorial is a part of our series of Python Package tutorials. You can find other Tkinter related topics too!

Tkinter is the most popular way to create Graphical User Interfaces (GUIs) in Python. For building GUIs, Tkinter provides developers with a number of standard widgets, including buttons, labels and text boxes.

Each of these widgets need to be positioned for user accessibility and widget focus, and then programmed with underlying application logic so they can work as intended in response to mouse clicks and other actions.

Positioning Widgets with Layout Managers

Tkinter has three built-in layout managers that use geometric methods to position widgets in an application frame:

  • pack() organizes widgets in horizontal and vertical boxes that are limited to left, right, top, bottom positions. Each box is offset and relative to each other.
  • place() places widgets in a two dimensional grid using x and y absolute coordinates.
  • grid() locates widgets in a two dimensional grid using row and column absolute coordinates.

Important : pack(), place(), and grid() should not be combined in the same master window. Instead choose one and stick with it.

Watch the video, which introduces the pack, place and grid code snippets below

Positioning Widgets With the Pack Layout Manager

pack is the easiest layout manager to use with Tkinter. Instead of declaring the precise location of a widget, pack() declares the positioning of widgets in relation to each other. However, pack() is limited in precision compared to place() and grid() which feature absolute positioning. For simple positioning of widgets vertically or horizontally in relation to each other, pack() is the layout manager of choice.

pack() has four padding options:

  • Internal padding
  • External padding
  • Padx , which pads along the x axis
  • Pady , which pads along the y axis

For more information about pack() and its options, refer to: How To Position Buttons in Tkinter With Pack

Vertical Positioning with Pack

In this example, three labels (widgets that contain text or images) are positioned vertically in relation to each other, and are not padded.

import tkinter as tk root = tk.Tk() test = tk.Label(root, text="Red", bg="red", fg="white") test.pack(side=tk.BOTTOM) test = tk.Label(root, text="Green", bg="green", fg="white") test.pack(side=tk.BOTTOM) test = tk.Label(root, text="Purple", bg="purple", fg="white") test.pack(side=tk.BOTTOM) tk.mainloop() 

Side-by-Side Positioning with Pack

In this example, three labels are positioned side by side in relation to each other, and are padded to separate them:

import tkinter as tk root = tk.Tk() test = tk.Label(root, text="red", bg="red", fg="white") test.pack(padx=5, pady=15, side=tk.LEFT) test = tk.Label(root, text="green", bg="green", fg="white") test.pack(padx=5, pady=20, side=tk.LEFT) test = tk.Label(root, text="purple", bg="purple", fg="white") test.pack(padx=5, pady=20, side=tk.LEFT) root.mainloop() 

Positioning Widgets With Place Layout Manager

place() lets you position a widget either with absolute x,y coordinates, or relative to another widget.

In this example, three labels are positioned diagonally using x,y coordinates.

from tkinter import * root = Tk() root.geometry('250x200+250+200') Label(root, text="Position 1 : x=0, y=0", bg="#FFFF00", fg="white").place(x=5, y=0) Label(root, text="Position 2 : x=50, y=40", bg="#3300CC", fg="white").place(x=50, y=40) Label(root, text="Position 3 : x=75, y=80", bg="#FF0099", fg="white").place(x=75, y=80) root.mainloop() 

Positioning Widgets With Grid Layout Manager

grid() positions widgets in a two dimensional grid of rows and columns similar to a spreadsheet.

In this example, four labels are positioned in a grid of rows and columns:

from tkinter import * root = Tk() Label(text="Position 1", width=10).grid(row=0, column=0) Label(text="Position 2", width=10).grid(row=0, column=1) Label(text="Position 3", width=10).grid(row=1, column=0) Label(text="Position 4", width=10).grid(row=1, column=1) root.mainloop() 

Positioning Tkinter.Ttk Widgets

The tkinter.ttk (Tile extension integrated into Tk) module provides access to the Tk themed widget set included in Tk 8.5 and greater.

Six new widgets are added by Ttk:

All six are subclasses of Widget.

There are differences in how the Ttk theme is coded, including alignment and padding options for the six new widgets. However, positioning with the pack, place and grid layout managers remains the same as Tk.

Ttk Usage

To start using Ttk, enter the following import statement in a Python console:

To override Tk widgets, the ttk import must follow the tk import:

from tkinter import * from tkinter.ttk import *

Importing tkinter.ttk after importing tkinter causes Ttk widgets to automatically replace the standard Tk widgets of Button, Checkbutton, Entry, Frame, Label, LabelFrame, Menubutton, PanedWindow, Radiobutton, Scale and Scrollbar.

Important: The basic idea is to separate as much as possible the code implementing a widget’s behavior from the code implementing its appearance ( Style() ).

Keep in mind that while Ttk widgets have a Style()padding option, it does not affect widget positioning.

Positioning Ttk widgets with Pack

In this example, a ttk.button is positioned with pack() and is padded.

from tkinter import * from tkinter.ttk import * root = Tk() # Style() padding adds pixels inside the Button. The widget’s position is not changed. ttk.Style().configure("TButton", padding=5, relief="flat") button1 = ttk.Button(text="Button Example") # pack() padding adds pixels outside the TButton. The widget’s position is changed. button1.pack(side = BOTTOM, padx= ) root.mainloop() 

Next steps

Now that you know how to add widgets using Python’s Tkinter, let’s move on to other things you can do with Tkinter:

Python For Data Science

Pre-bundled with the most important packages Data Scientists need, ActivePython is pre-compiled so you and your team don’t have to waste time configuring the open source distribution. You can focus on what’s important–spending more time building algorithms and predictive models against your big data sources, and less time on system configuration.

  • pandas (data analysis)
  • NumPy (multi-dimensional arrays)
  • SciPy (algorithms to use with numpy)
  • HDF5 (store & manipulate data)
  • Matplotlib (data visualization)
  • Jupyter (research collaboration)
  • PyTables (managing HDF5 datasets)
  • HDFS (C/C++ wrapper for Hadoop)
  • pymongo (MongoDB driver)
  • SQLAlchemy (Python SQL Toolkit)

Источник

Оцените статью