Я пытаюсь сделать простой тест с несколькими страницами и переключателями, используя 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()