Python Tkinter Radiobutton возвращает значение для неправильного экземпляра - PullRequest
0 голосов
/ 23 сентября 2018

Я пытаюсь сделать простой тест с несколькими страницами и переключателями, используя Tkinter.Я нахожусь на этапе, когда мне нужно получить выбранные радиокнопки, чтобы сформулировать какой-то ответ.

Когда я нажимаю тестовую кнопку «нажми меня», предполагается вывести IntVar для радиокнопок в вопросе на текущей странице.Тем не менее, он получает IntVar для Page2, даже если на странице 1.

Если у меня есть только одна страница, он работает как положено.

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()

1 Ответ

0 голосов
/ 23 сентября 2018

Ваша основная проблема - использование глобальных переменных для отслеживания страниц и вопросов.В ваших классах 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()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...