Python Tkinter单选按钮返回错误实例的值

2024-09-29 22:01:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着做一个简单的测验与多页和单选按钮使用Tkinter。我现在正处于这样一个阶段,我需要选择单选按钮来做出某种反应。你知道吗

当我按下测试“press me”按钮时,它应该输出当前页面上问题中单选按钮的IntVar。但是,它会得到Page2的IntVar,即使在Page1上也是如此。你知道吗

如果我只有一个页面,它会像预期的那样工作。你知道吗

import tkinter as tk

#a single frame with a question and multiple options
class Question(tk.Frame):
    def __init__(self, *options, **kwargs):
        tk.Frame.__init__(self, *options, **kwargs)
        global self1
        self1 = self

    def Configure(notneeded, *options, **keywords):
        print("-" * 40)
        questionframe=tk.Frame(self1)
        questionframe.pack(side="top", fill="x")        
        for kw in keywords:
            if kw == "question":
                tk.Label(questionframe, text=keywords[kw]).pack(anchor=tk.W)
                print(keywords[kw])
        print("-" * 40)
        buttonframe = tk.Frame(self1)
        buttonframe.pack(side="top", fill="x")
        global v
        v = tk.IntVar() #variable for keeping track of radiobuttons
        Buttons = []
        i = 1
        for option in options:
            b = tk.Radiobutton(buttonframe, text=option, variable=v, 
value=i)
            b.pack(anchor=tk.W)
            Buttons.append(b)
            i += 1
            print(option)
        return Buttons

    #return the index of the selected radiobutton (starts from 1)
    def GetSelectedIndex(notneeded):
        return v.get()

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)
        def ButtonPress():
            print("Selected Option:", q1.GetSelectedIndex())
        global q1
        q1 = Question(self)
        q1.Configure("Car", "Minecart", "Riding a spider", "Flight",
            question="How would you prefer to get around?")
        q1.pack(side="bottom", fill="both", expand=True)
        tk.Button(self, command=ButtonPress, text="press me - 1").pack()
   def GetSelectedIndex(notneeded):
        return q1.GetSelectedIndex()

class Page2(Page):
   def __init__(self, *args, **kwargs):
        Page.__init__(self, *args, **kwargs)
        def ButtonPress():
            print("Selected Option:", q1.GetSelectedIndex())
        global q1
        q1 = Question(self)
        q1.Configure("Day", "Night",
        question="Do you prefer day or night time?")
        q1.pack(side="bottom", fill="both", expand=True)
        tk.Button(self, command=ButtonPress, text="press me - 2").pack()
   def GetSelectedIndex(notneeded):
        return q1.GetSelectedIndex()

CurrentPage = 0
MaxPages = 1
def ChangePage(amount):
    global CurrentPage
    CurrentPage += amount
    CurrentPage = sorted((0, CurrentPage, MaxPages))[1]
    print("Current Page: " + str(CurrentPage))
    return CurrentPage

class MainView(tk.Frame):     
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        def On_Back():
            ChangePage(-1)
            Pages[CurrentPage].lift()
        def On_Next():
            ChangePage(1)
            Pages[CurrentPage].lift()
        def GetP1Value():
            print("Selected Option:", Pages[0].GetSelectedIndex())

        #the correct value is output when Page2(self) is removed
        Pages = [Page1(self), Page2(self)]

        Frame_Buttons = tk.Frame(self)
        Frame_Buttons.pack(side="bottom", fill="x", expand=False)
        Button_Next = tk.Button(Frame_Buttons, text="Next", 
command=On_Next).pack(side="right")
        Button_Back = tk.Button(Frame_Buttons, text="Back", 
command=On_Back).pack(side="right")
        tk.Button(Frame_Buttons, text="get page 1", 
command=GetP1Value).pack(side="right")
        Frame_Pages = tk.Frame(self)
        Frame_Pages.pack(side="top", fill="both", expand=True)
        for page in Pages:
            page.place(in_=Frame_Pages, x=0, y=0, relwidth=1, relheight=1)
        Pages[0].show()

if __name__ == "__main__":
    root = tk.Tk()
    main = MainView(root)
    main.pack(side="top", fill="both", expand=True)
    root.wm_geometry("300x300")
    root.mainloop()

Tags: selfinitdefargspagesframesidepack
1条回答
网友
1楼 · 发布于 2024-09-29 22:01:27

您的主要问题是使用全局变量来跟踪页面和问题。在Page1和Page2类中,使用相同的名称声明全局变量,并在实例化后续页面时覆盖self1值。特别是考虑到你的应用程序使用基于类的结构,全局变量应该完全去掉。幸运的是,基于类的应用程序有一个内置的机制来处理数据存储—它是self变量。你知道吗

参见下面的工作示例。问题IntVar()对象与每个单独的类实例相关联,因此类的内部行为将引用正确的IntVar()值。请参阅声明self.q1 = IntVar()的行self.语句将IntVar()分配给类实例,并在Configure方法完成后将变量作为类成员持久化。通过这种方式,q1的值可以很容易地为每个单独的页面访问和更新,而不是为每个添加的问题覆盖。你知道吗

import tkinter as tk

#a single frame with a question and multiple options
class Question(tk.Frame):
    def __init__(self, *options, **kwargs):
        tk.Frame.__init__(self, *options, **kwargs)
        # global self1
        # self1 = self

    def Configure(self, *options, **keywords):
        print("-" * 40)
        questionframe=tk.Frame(self)
        questionframe.pack(side="top", fill="x")        
        for kw in keywords:
            if kw == "question":
                tk.Label(questionframe, text=keywords[kw]).pack(anchor=tk.W)
                print(keywords[kw])
        print("-" * 40)
        buttonframe = tk.Frame(self)
        buttonframe.pack(side="top", fill="x")
        # global v
        self.v = tk.IntVar() #variable for keeping track of radiobuttons
        Buttons = []
        i = 1
        for option in options:
            b = tk.Radiobutton(buttonframe, text=option, variable=self.v, 
value=i)
            b.pack(anchor=tk.W)
            Buttons.append(b)
            i += 1
            print(option)
        return Buttons

    #return the index of the selected radiobutton (starts from 1)
    def GetSelectedIndex(self):
        return self.v.get()

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)
        def ButtonPress():
            print("Selected Option:", self.q1.GetSelectedIndex())
        # global q1
        self.q1 = Question(self)
        self.q1.Configure("Car", "Minecart", "Riding a spider", "Flight",
            question="How would you prefer to get around?")
        self.q1.pack(side="bottom", fill="both", expand=True)
        tk.Button(self, command=ButtonPress, text="press me - 1").pack()
   def GetSelectedIndex(self):
        return self.q1.GetSelectedIndex()

class Page2(Page):
   def __init__(self, *args, **kwargs):
        Page.__init__(self, *args, **kwargs)
        def ButtonPress():
            print("Selected Option:", self.q1.GetSelectedIndex())
        # global q1
        self.q1 = Question(self)
        self.q1.Configure("Day", "Night",
        question="Do you prefer day or night time?")
        self.q1.pack(side="bottom", fill="both", expand=True)
        tk.Button(self, command=ButtonPress, text="press me - 2").pack()
   def GetSelectedIndex(self):
        return self.q1.GetSelectedIndex()

CurrentPage = 0
MaxPages = 1
def ChangePage(amount):
    global CurrentPage
    CurrentPage += amount
    CurrentPage = sorted((0, CurrentPage, MaxPages))[1]
    print("Current Page: " + str(CurrentPage))
    return CurrentPage

class MainView(tk.Frame):     
    def __init__(self, *args, **kwargs):
        tk.Frame.__init__(self, *args, **kwargs)
        def On_Back():
            ChangePage(-1)
            Pages[CurrentPage].lift()
        def On_Next():
            ChangePage(1)
            Pages[CurrentPage].lift()
        def GetP1Value():
            print("Selected Option:", Pages[0].GetSelectedIndex())

        #the correct value is output when Page2(self) is removed
        Pages = [Page1(self), Page2(self)]

        Frame_Buttons = tk.Frame(self)
        Frame_Buttons.pack(side="bottom", fill="x", expand=False)
        Button_Next = tk.Button(Frame_Buttons, text="Next", 
command=On_Next).pack(side="right")
        Button_Back = tk.Button(Frame_Buttons, text="Back", 
command=On_Back).pack(side="right")
        tk.Button(Frame_Buttons, text="get page 1", 
command=GetP1Value).pack(side="right")
        Frame_Pages = tk.Frame(self)
        Frame_Pages.pack(side="top", fill="both", expand=True)
        for page in Pages:
            page.place(in_=Frame_Pages, x=0, y=0, relwidth=1, relheight=1)
        Pages[0].show()

if __name__ == "__main__":
    root = tk.Tk()
    main = MainView(root)
    main.pack(side="top", fill="both", expand=True)
    root.wm_geometry("300x300")
    root.mainloop()

相关问题 更多 >

    热门问题