我正在尝试使用第一个答案here创建GUI。我遇到了一些问题,因为我不完全理解应该如何连接。
我正在使用一个类创建一个盒子网格。每个框使用bind在单击时调用某个函数。
我在哪里创建Many_Boxes类?在底部看到了我正在尝试做的一个例子。
在Main类的Many_Boxes类中,我有一个绑定到函数的动作。我在哪里放这个功能?我该如何调用该功能?如果我想从Nav类调用该函数怎么办?
我有:
class Nav(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
class Main(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.parent = parent
self.hand_grid_dict = self.create_hand_grid()
class Many_Boxes:
<<<<<<<<< bunch of code here >>>>>>>>>>>>>>
self.hand_canvas.bind("<Button-1>", lambda event: button_action(canvas_hand)) <<<<<< WHAT DO I NAME THIS??? self.parent.....?
class MainApplication(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
self.navbar = Nav(self)
self.main = Main(self)
self.navbar.pack(side="left", fill="y")
self.main.pack(side="right", fill="both", expand=True)
if __name__ == "__main__":
root = tk.Tk()
MainApplication(root).grid(row=1, column=1)
root.mainloop()
我把它放在哪里:
def create_grid(self):
for x in y:
your_box = self.Many_Boxes(.......)
答案 0 :(得分:0)
如果我正确理解你的问题,就不需要创建一个类来创建框。您所要做的就是用Many_Boxes
函数替换create_hand_grid
类,并定义button_action
函数:
import tkinter as tk
class Navbar(tk.Frame):
def __init__(self, parent):
self.parent = parent
super().__init__(self.parent)
tk.Label(self.parent, text='Navbar').pack()
tk.Button(self.parent, text='Change Color', command=self.change_color).pack()
def change_color(self):
# access upwards to MainApp, then down through Main, then ManyBoxes
self.parent.main.many_boxes.boxes[0].config(bg='black')
class ManyBoxes(tk.Frame):
def __init__(self, parent):
self.parent = parent
super().__init__(self.parent)
self.boxes = []
self.create_boxes()
def button_action(self, e):
print('%s was clicked' % e.widget['bg'])
def create_boxes(self):
colors = ['red', 'green', 'blue', 'yellow']
c = 0
for n in range(2):
for m in range(2):
box = tk.Frame(self, width=100, height=100, bg=colors[c])
box.bind('<Button-1>', self.button_action)
box.grid(row=n, column=m)
self.boxes.append(box)
c += 1
class Main(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.parent = parent
self.many_boxes = ManyBoxes(self)
self.many_boxes.pack()
class MainApp(tk.Frame):
def __init__(self, parent):
super().__init__(parent)
self.navbar = Navbar(self)
self.navbar.pack(fill=tk.Y)
self.main = Main(self)
self.main.pack(fill=tk.BOTH, expand=True)
if __name__ == "__main__":
root = tk.Tk()
MainApp(root).pack()
root.mainloop()
我已填写create_hand_grid
和button_action
,因此您可以复制粘贴代码并查看其是否有效。