Vam*_*oos 1 python tkinter python-3.x
在下面的代码中,我创建了一个窗口和一个框架.
代码1:
import tkinter as tk
class MainApp(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
button = tk.Button(parent, text="a button")
button.pack()
root = tk.Tk()
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
代码2:
import tkinter as tk
class MainApp(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
button = tk.Button(self, text="a button")
button.pack()
root = tk.Tk()
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
然后我以两种方式创建一个按钮(Button(self)
和Button(parent)
).问题是:在这两种情况下,按钮是否都放在我创建的框架中(就像那样:) tk.Frame.__init__(self, parent)
,它们旁边都有,或者旁边有一个按钮,里面有一个按钮?如果两者都在其中创建,那么tk.Frame.__init__(self, parent)
如果内部没有任何内容,那么有什么意义呢?
窗口小部件(当然)在其父窗口中打包,否则指定窗口小部件的父窗口没有多大意义(除非有其他特殊原因).因此,在第一种情况下,按钮被打包在根(框架的父级)中,而在第二种情况下,按钮被打包在框架本身内.
为了更好地了解正在发生的事情,最好的解决方案是设置框架和根的背景颜色.请参阅以下示例:
代码1:
import tkinter as tk
class MainApp(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, bg="blue")
self.parent = parent
button = tk.Button(parent, text="a button")
button.pack()
root = tk.Tk()
root.geometry("200x200+300+300")
root.config(background="yellow")
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
结果1
代码2:
import tkinter as tk
class MainApp(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, bg="blue")
self.parent = parent
button = tk.Button(self, text="a button")
button.pack()
root = tk.Tk()
root.geometry("200x200+300+300")
root.config(background="yellow")
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
结果2
另请注意,在使用某些小部件填充框架之前,框架没有大小.另请注意,您正在扩展框架(或MainApp
)并使其填充打扰垂直和水平方向,因此蓝色占据了最后一种情况下的所有窗口.
在下面的代码中,我在其中创建了一个窗口和一个框架。
这是一个不正确的说法。您正在创建一个继承自tk.Frame
. 在类中,self
代表那个框架。在课外,那个框架是app
.
然后我以两种方式创建一个按钮(Button(self) 和 Button(parent))。现在的问题是:做的按钮,在这两种情况下,得到安置的框架,我创建了(这样的:tk.Frame的init(个体经营,母体)),都在它旁边,或者一个在它旁边,一个里面?
当你这样做时Button(self)
,按钮是框架的子元素,因此会出现在框架内。
当您这样做时Button(parent)
,按钮是父窗口的子窗口(在本例中为根窗口),因此将出现在框架之外。
通过为框架赋予独特的颜色,您可以轻松地看到这一点。
import tkinter as tk
class MainApp(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent, background="pink")
self.parent = parent
button = tk.Button(parent, text="a button")
button.pack()
root = tk.Tk()
app = MainApp(root)
app.pack(fill="both", expand=True)
root.mainloop()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
5956 次 |
最近记录: |