Tkinter:你能在网格中放置一个框架或网格吗?

时间:2021-07-02 15:42:07

标签: python tkinter

我正在尝试制作一个元素周期表程序,我想在网格中设置一个网格

Here is an image of the effect

这可能吗,如果可以,如何。 谢谢。

1 个答案:

答案 0 :(得分:0)

是的,您可以,只需将父框架作为参数提供给辅助框架,就像 tkinter 中的任何其他小部件一样:

variable = tk.Widget(parent, widget, specifics)

在您基本上希望为所有元素显示相同信息的情况下,我将创建一个继承自 tk.Frame 类的子类并将所有相关信息传递给它,这样您只需组织您的小框架一次。

你可能想从这样的事情开始:

import tkinter as tk

class Application(tk.Tk):
    
    def __init__(self, *args, **kwargs):
        tk.Tk.__init__(self, *args, **kwargs)
        
        self.mainframe = tk.Frame(self)
        self.mainframe.pack(fill="both", expand = True)
        
        
        # note how we're now not calling for the tk.Frame class anymore,
        # since we have our own custom one
        # when calling our class we can now pass information to it
        # right now only the name
        self.vanadium = ElementFrame(self.mainframe, "Vanadium")
        #placing in the main frame
        self.vanadium.grid(row = 0, column = 0)
        
        self.chromium = ElementFrame(self.mainframe, "Chromium")
        #placing in the main frame
        self.chromium.grid(row = 0, column = 1)
        
        self.niobium = ElementFrame(self.mainframe, "Niobium")
        #placing in the main frame
        self.niobium.grid(row = 1, column = 0)
        
        self.molybdenum = ElementFrame(self.mainframe, "Molybdenum")
        #placing in the main frame
        self.molybdenum.grid(row = 1, column = 1)
        
        
class ElementFrame(tk.Frame):
    
    # here we are defining what variables need to be passed for a successful call
    def __init__(self, parent, element):
        tk.Frame.__init__(self, parent)
        
        #pass variables through, like abbreviation, number, etc.
        self.element = element
        #organize your elements frame
        self.elementlabel = tk.Label(self, text = element)
        self.elementlabel.grid(row = 0, column = 0)
        
        
        
app = Application()
app.mainloop()

相关问题