我正在编写一个 Tkinter 程序,我可以在其中制作多个框架,我可以选择它们相对于彼此的位置,所以我决定使用 grid() 来决定哪个框架在哪里。我还有一个创建按钮/标签/条目的 AppButton 类。我正在尝试传入我希望在其中创建按钮的框架,并使用网格来确定其相对于创建它的框架的位置。
但是目前,按钮并没有在我尝试传递的框架中制作,而是使用与框架相同的网格,并且只是放在那儿,回顾起来是有道理的。
我的问题是,如何更改此设置,使按钮的网格成为仅相对于创建它的框架的单独网格?这样,如果我四处移动框架,按钮也会移动,但它们在框架中的相对位置保持不变。
现在框架和按钮共享同一个网格,这就是它们的位置是如何确定的。
import Tkinter as tk
import tkFileDialog as tkfd
class AppButton:
#simple button construction
#create a button with chosen arguments
def create_button(self, words, rownum, frame):
btn = tk.Button(frame, text = words)
btn.grid(row = rownum, column = 2)
def create_entry(self, rownum, frame):
txt = tk.Entry(frame)
txt.grid(row = rownum, column = 1)
def create_label(self, words, rownum, frame):
lbl = tk.Label(frame, text = words)
lbl.grid(row = rownum, column = 0)
#input is composed of a Label, an Entry, and a Button. calls the three funcs above
def create_input(self, words, rownum, frame):
self.create_label(words, rownum, frame)
self.create_entry(rownum, frame)
self.create_button("OK", rownum, frame)
class Application(tk.Frame):
"""A GUI application that creates multiple buttons"""
#create a class variable from the root(master) called by the constructor
def __init__(self, master):
self.master = master
master.title("The best GUI")
tk.Frame.__init__(self, master, width=200, height=200)
self.grid(row = 0, column = 0)
def new_frame(self, master, color, row, column):
frame = tk.Frame(master, width=200, height=200, bg=color)
frame.grid(row = row, column = column)
return frame
if __name__ == "__main__":
root = tk.Tk()
root.title("Button Test Launch")
app = Application(root)
appbutton = AppButton()
frame1 = app.new_frame(root, "red", 3, 1)
frame2 = app.new_frame(root, "blue", 2, 2)
appbutton.create_input("test1", 0, root)
appbutton.create_input("test2", 1, root)
appbutton.create_input("test3", 2, root)
appbutton.create_input("test4", 3, root)
root.mainloop()
这是它现在的样子的图片: Current GUI
我想要的最终结果是让“test1 ______ [OK]”完全位于其中一个框架中。
请您参考如下方法:
您告诉按钮使用 root 作为它们的父级。相反,您应该传入框架:
appbutton.create_input("test1", 0, frame1)
appbutton.create_input("test2", 1, frame1)
appbutton.create_input("test3", 2, frame2)
appbutton.create_input("test4", 3, frame2)
