为什么没有呈现托管小部件

时间:2017-06-05 20:09:55

标签: tkinter

我想要呈现左侧自定义小部件3次。左,中,右。

我试图关注并混合我找到的一些例子,但我只提供了一个小部件。

我添加了colout以获得一些线索,但我无法找到我做错的事。

这是代码:

import sys
import tkinter as tk
#import tkinter.ttk, Font, Label, Frame as tk
#import tkinter.ttk as tk

#https://stackoverflow.com/questions/27614037/python-3-tkinter-create-text-widget-covering-100-width-with-grid?rq=1
# https://stackoverflow.com/questions/7591294/how-to-create-a-self-resizing-grid-of-buttons-in-tkinter
# http://effbot.org/tkinterbook/grid.htm

# 02. Pruebo cambiando llamada de funcion de clase a metodo de instancia  

class   Cuadro(tk.Frame):
    def __init__(self, parent, *args, **kargs):

        # super().__init__(root)
        tk.Frame.__init__(self, parent, *args, **kargs)

        #Create & Configure frame 

        frame = tk.Frame(parent)       
        frame.grid(row=0, column=0, sticky="NSEW")



        #Create a 3x3 (rows x columns) grid of labels inside the frame
        for row_index in range(3):
        #tk.Grid.rowconfigure(frame, row_index, weight=1)               # version 02
            frame.rowconfigure(row_index, weight=1)                     # version 02
            for col_index in range(3):
                #tk.Grid.columnconfigure(frame, col_index, weight=1)    # version 02
                frame.columnconfigure(col_index, weight=1)              # version 02
                lbl = tk.Label(frame, text = str((row_index *3) + col_index + 1)) #create a button inside frame 
                #lbl.grid(row=row_index, column=col_index, sticky=N+S+E+W)
                lbl.grid(row=row_index, column=col_index, sticky="NSEW")



#Create & Configure root
class   Application(tk.Frame):
    def __init__(self, parent):

        tk.Grid.rowconfigure   (parent, 0, weight=1)
        tk.Grid.columnconfigure(parent, 0, weight=1)
        tk.Grid.columnconfigure(parent, 1, weight=1)
        tk.Grid.columnconfigure(parent, 2, weight=1)
        self.cuadro1 = Cuadro(parent)
        self.cuadro1.config(background="red")
        self.cuadro1.grid(row=0, column=0, sticky="NSEW")     
        self.cuadro2 = Cuadro(parent)
        self.cuadro2.config(bg="green")
        self.cuadro2.grid(row=0, column=1, sticky="NSEW")
        self.cuadro3 = Cuadro(parent)
        self.cuadro3.config(bg="blue")
        self.cuadro3.grid(row=0, column=2, sticky="NSEW")


def main():
    root = tk.Tk()
    root.title(sys.argv[0])    # version 02

    myapp = Application(root)
    root.mainloop()

if __name__ == '__main__':
    main()

这就是结果:

http://imgur.com/XROp68R

有什么问题?

1 个答案:

答案 0 :(得分:0)

你的三个Cuadro对象根本没有内容 - 它们是有效的帧,因为你继承自tk.Frame并且调用了超类__init__(),但你对它们完全没有做任何事情。相反,每个人都创建了一个完全独立的框架,没有连接到Cuadro本身,并将其放置在父视图中的row = 0,column = 0。这些中的每一个都覆盖了前一个,并且最初放置在行= 0,列= 0的红色Cuadro,因此您最终获得了3x3网格的单个可见副本,并且没有红色区域。

你在应用程序中犯了同样的错误 - 它是一个有效的框架,但你没有添加任何内容,而是你创建了每个Cuadro作为应用程序父代的直接子代(Tk根窗口)。

只有像这样创建小部件的类是完全有效的,但如果你不打算将它们用作小部件本身,它们不应该从Tk小部件类派生。

相关问题