我是一名Python初學者。我在使用不同類的變量時遇到了問題。請幫忙。 這裏是Using buttons in Tkinter to navigate to different pages of the application?在不同的類中使用變量
import Tkinter as tk
class Page(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
def show(self):
self.lift()
class Page1(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
label = tk.Label(self, text="This is page 1")
label.pack(side="top", fill="both", expand=True)
entry = tk.Entry(self)
entry.pack()
class Page2(Page):
def __init__(self, *args, **kwargs):
Page.__init__(self, *args, **kwargs)
label = tk.Label(self, text="This is page 2")
label.pack(side="top", fill="both", expand=True)
text = tk.Text(self, entry.get())
root.after(...)
class MainView(tk.Frame):
def __init__(self, *args, **kwargs):
tk.Frame.__init__(self, *args, **kwargs)
p1 = Page1(self)
p2 = Page2(self)
buttonframe = tk.Frame(self)
container = tk.Frame(self)
buttonframe.pack(side="top", fill="x", expand=False)
container.pack(side="top", fill="both", expand=True)
p1.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
p2.place(in_=container, x=0, y=0, relwidth=1, relheight=1)
b1 = tk.Button(buttonframe, text="Page 1", command=p1.lift)
b2 = tk.Button(buttonframe, text="Page 2", command=p2.lift)
b1.pack(side="left")
b2.pack(side="left")
p1.show()
if __name__ == "__main__":
root = tk.Tk()
main = MainView(root)
main.pack(side="top", fill="both", expand=True)
root.wm_geometry("400x400")
root.mainloop()
示例代碼然後它有兩個問題:
NameError: global name 'entry' is not defined
NameError: global name 'root' is not defined
如何使用這些變量?請幫忙!
似乎導入無法正常工作。確定Tkinter安裝正確嗎? –
爲什麼我需要這麼多課程?在變量條目的情況下,你已經在Page1類中聲明該變量並在Page2類中使用它。當變量綁定到它們的類時,這種情況就不會發生。如果您真的想這樣做,請將條目聲明爲類變量,以便您可以使用Page1.entry訪問相同的條目。 – DineshKumar
您確實需要熟悉範圍的概念以及它們與獲取屬性的區別。 – direprobs