在Python tkinter中的Tk类中使用框架类
在下面的示例中,我尝试在MainW()中使用Frame1()。我尝试了下面代码的许多变体。问题是帧对象颜色和行跨度根本没有改变。我知道在MainW()中使用Frame1()存在问题。有人能指出错误吗在Python tkinter中的Tk类中使用框架类,python,class,tkinter,Python,Class,Tkinter,在下面的示例中,我尝试在MainW()中使用Frame1()。我尝试了下面代码的许多变体。问题是帧对象颜色和行跨度根本没有改变。我知道在MainW()中使用Frame1()存在问题。有人能指出错误吗 from tkinter import * class Frame1(Frame): def __init__(self, parent): Frame.__init__(self, parent, bg="red") self.pa
from tkinter import *
class Frame1(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, bg="red")
self.parent = parent
self.widgets()
def widgets(self):
self.text = Text(self)
self.text.insert(INSERT, "Hello World\t")
self.text.insert(END, "This is the first frame")
self.text.grid(row=0, column=0)
class MainW(Tk):
def __init__(self, parent):
Tk.__init__(self, parent)
self.parent = parent
self.mainWidgets()
def mainWidgets(self):
self.label = Label(self, text="Main window label")
self.label.grid(row=0, column=0)
self.window = Frame1(self)
self.window.grid(row=0, column=10, rowspan=2)
if __name__=="__main__":
app = MainW(None)
app.mainloop()
这是不是我想要的输出。我需要帧的背景红色和行间距为1:
谢谢您无法看到框架颜色,因为您放置了填充所有框架的小部件 如果添加边距(
padx
,pady
),则可以看到边框颜色
self.text.grid(row=0, column=0, padx=20, pady=20)
您无法看到行span
,因为第二行是空的单元格。空单元格没有宽度和高度。在第二行添加标签,并查看行span
的工作方式
from tkinter import *
class Frame1(Frame):
def __init__(self, parent):
Frame.__init__(self, parent, bg="red")
self.parent = parent
self.widgets()
def widgets(self):
self.text = Text(self)
self.text.insert(INSERT, "Hello World\t")
self.text.insert(END, "This is the first frame")
self.text.grid(row=0, column=0, padx=20, pady=20) # margins
class MainW(Tk):
def __init__(self, parent):
Tk.__init__(self, parent)
self.parent = parent
self.mainWidgets()
def mainWidgets(self):
self.label1 = Label(self, text="Main window label", bg="green")
self.label1.grid(row=0, column=0)
self.label2 = Label(self, text="Main window label", bg="yellow")
self.label2.grid(row=1, column=0)
self.window = Frame1(self)
self.window.grid(row=0, column=10, rowspan=2)
if __name__=="__main__":
app = MainW(None)
app.mainloop()
什么颜色?红色您放置了Text()
,但看不到边框颜色Text()
不是透明的-它有自己的颜色。网格有什么问题?网格中的单元格在您将小部件放入此单元格之前没有宽度和高度。