user1104854
user1104854

Reputation: 2167

label layout using grid in tkinter

I'm having some trouble figuring out how to use grid properly with tkinter. I just want two labels to appear side by side.

When I do the following, they appear in a separate window from my app. I'm confused because I have buttons on my app that appear as I want them(not using grid), but I can't quite figure out the labels in a grid.

    //this is just a snippet from a function
    self.root = tk.Tk()
    tk.Label(master=self.root, text=directory).grid(row=0,column=0)
    tk.Label(master=self.root, text=directory).grid(row=0,column=1)

The root window is created in a different part of the app, so all I'm doing here is making another one (I think). I just want the labels to appear in the window that has already been created but I can't figure out what I'm supposed to reference it to. This is in a separate file that includes the file with the code above

from Tkinter import *
import tkinter as tk
import widgetActions
import shutil

class mywidgets(widgetActions.Actions):

def __init__(self,root):
    frame = tk.Frame(root)
    self.makeMenuBar(frame)
    frame.pack()
    frame.config(width=400)
    self.body()
    return


def makeMenuBar(self,frame):
    menubar = Frame(frame,relief=RAISED,borderwidth=1)
    menubar.pack()


    mb_file = Menubutton(menubar,text='file')
    mb_file.pack(side=LEFT)
    mb_file.menu = Menu(mb_file)


    mb_file.menu.add_command(label='open', command = self.openfile)
    mb_file.menu.add_command(label='close', command = menubar.quit)

    mb_file['menu'] = mb_file.menu
    return

def body(self):
    self.filename()


def main():
root = tk.Tk()
k=mywidgets(root)
root.title('menu bar')
root.mainloop()
main()

Upvotes: 0

Views: 2566

Answers (2)

BigGibb
BigGibb

Reputation: 317

To position the 2 labels side by side i.e label1 and label2:
label1.grid(column=0, row=0)
label2.grid(column=1, row=0)

That should do it

Upvotes: 0

Bryan Oakley
Bryan Oakley

Reputation: 385860

You cannot create two instances of Tk. As you observed, you will get two windows. That's not the only problem, just the most obvious one.

You need to pass in a reference to the winget that is to contain these labels. Or, store the root window as a global variable, or as an attribute of an object.

Upvotes: 2

Related Questions