我使用来自 Steven M. Vascellaro 示例Switch between two frames in tkinter的多帧窗口。
而且我不知道是否可以使用全局变量,因为每次更改时每个框架都会被破坏。如果我单击第二个按钮并转到StartPage
并在那里执行某项操作并返回到StartPage,则必须激活PageOne
上的第一个按钮(共2个按钮),必须激活第一个按钮。
如果我在global
类中声明StartPage
_tkinter.TclError: invalid command name ".!startpage.!button2"
如果我在PageOne
类中声明了它
NameError: name 'install_svc' is not defined
不是个好主意,但我想到了第三帧,我再次定义了按钮。
EDIT1:
class MyGUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
self.geometry("400x300")
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
def quit_app(self):
self._frame.destroy()
self.destroy()
class StartPage(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
global install_svc
class PageOne(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
def entry_check(self,parent):
global install_svc
答案 0 :(得分:1)
在根级别(全局范围)声明并初始化install_svc
。语句global install_svc
本身不会自动神奇地创建全局范围内的变量:它只会查找具有该名称的全局变量,但是,如果您尝试使用该变量而没有先给它分配任何东西,它会抛出NameError
。
install_svc = None # Or some other initial value
class MyGUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
self.geometry("400x300")
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
def quit_app(self):
self._frame.destroy()
self.destroy()
class StartPage(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
global install_svc
# You can use install_svc safely
print(install_svc)
class PageOne(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
def entry_check(self,parent):
global install_svc
# You can use install_svc safely
print(install_svc)
您还可以执行try..except
来检查变量是否存在,但这将非常难看(至少对我而言),并且您将需要在所有地方进行此类检查:< / p>
class MyGUI(tk.Tk):
def __init__(self):
tk.Tk.__init__(self)
self._frame = None
self.switch_frame(StartPage)
self.geometry("400x300")
def switch_frame(self, frame_class):
"""Destroys current frame and replaces it with a new one."""
new_frame = frame_class(self)
if self._frame is not None:
self._frame.destroy()
self._frame = new_frame
self._frame.pack()
def quit_app(self):
self._frame.destroy()
self.destroy()
class StartPage(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
global install_svc
try:
install_svc
except NameError:
install_svc = None # Or some initial value
class PageOne(tk.Frame):
def __init__(self, parent):
tk.Frame.__init__(self, parent)
def entry_check(self,parent):
global install_svc
try:
install_svc
except NameError:
install_svc = None # Or some initial value