我正在尝试创建一个GUI,如下图所示:
以下是代码:
#! /usr/bin/python3
import tkinter as tk
# CLASS FOR OWN PANEL:
class Mypanel(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self.label = tk.Label(self, text="Enter here:")
self.entry = tk.Entry(self)
self.label.pack()
self.entry.pack()
# FN FOR BUTTON:
def adder():
main_label.set((panel1.entry.get() + panel2.entry.get()))
# CREATE GUI ELEMENTS:
main_window = tk.Tk() # CREATE MAIN WINDOW
panel1 = Mypanel() # CREATE A PANEL
panel2 = Mypanel() # CREATE ANOTHER PANEL
main_label = tk.Label(main_window, text="Press button to get values.")
main_button = tk.Button(main_window, text="Get values.", command=adder)
# PACK ALL GUI ELEMENTS IN main WINDOW
panel1.pack()
panel2.pack()
main_label.pack()
main_button.pack()
# SHOW MAIN WINDOW:
main_window.mainloop()
但是,它给出了以下错误:
$ ./guipanels.py
Traceback (most recent call last):
File "./guipanels.py", line 29, in <module>
panel1.pack()
File "/usr/lib/python3.5/tkinter/__init__.py", line 1961, in __getattr__
return getattr(self.tk, attr)
AttributeError: '_tkinter.tkapp' object has no attribute 'pack'
问题出在哪里?如何解决?谢谢你的帮助。
答案 0 :(得分:2)
您需要的不是Tk
课程,而是Frame
而不是:
import tkinter as tk
# CLASS FOR OWN PANEL:
class Mypanel(tk.Frame):
def __init__(self, master=None, **kwargs):
super().__init__(master, kwargs)
self.label = tk.Label(self, text="Enter here:")
self.entry = tk.Entry(self)
self.label.pack()
self.entry.pack()
# def on_button(self):
# print(self.entry.get())
# FN FOR BUTTON:
def adder():
main_label.set((panel1.entry.get() + panel2.entry.get()))
# CREATE GUI ELEMENTS:
main_window = tk.Tk() # CREATE MAIN WINDOW
panel1 = Mypanel(main_window) # CREATE A PANEL
panel2 = Mypanel(main_window) # CREATE ANOTHER PANEL
main_label = tk.Label(main_window, text="Press button to get values.")
main_button = tk.Button(main_window, text="Get values.", command=adder)
# PACK ALL GUI ELEMENTS IN main WINDOW
panel1.pack()
panel2.pack()
main_label.pack()
main_button.pack()
# SHOW MAIN WINDOW:
main_window.mainloop()
您可以将类Tk
视为主应用程序,并将小部件放入其中。代码中应该只有一个Tk
。
答案 1 :(得分:2)
你的意思是继承tk.PanedWindow
吗?
试试这个:
class Mypanel(tk.PanedWindow):
def __init__(self, mainwindow):
super(Mypanel, self).__init__(mainwindow)
self.label = tk.Label(self, text="Enter here:")
self.entry = tk.Entry(self)
self.label.pack()
self.entry.pack()
# def on_button(self):
# print(self.entry.get())
并将代码中的main_window
传递给面板:
main_window = tk.Tk() # CREATE MAIN WINDOW
panel1 = Mypanel(main_window) # CREATE A PANEL
panel2 = Mypanel(main_window) # CREATE ANOTHER PANEL