简体   繁体   English

标签布局在tkinter中使用网格

[英]label layout using grid in tkinter

I'm having some trouble figuring out how to use grid properly with tkinter. 我在弄清楚如何使用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 . 您无法创建两个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. 您需要传入对包含这些标签的winget的引用。 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: 要并排放置2个标签,即label1和label2:
label1.grid(column=0, row=0)
label2.grid(column=1, row=0)

That should do it 应该这样做

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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