简体   繁体   中英

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()

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.

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

That should do it

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM