I have two OptionMenu
widgets in a frame in my tkinter application. The first widget is a drop-down menu with chapter numbers of a book, the second is another drop-down menu that should show page numbers for the chapter that was selected in the first menu, and when a page is selected the text form that page should show up on the screen.
So, when a selection is made in the first OptionMenu
widget, I need to update the contents of the second OptionMenu
widget. I've been using the update_pages()
function below to update the second widget, basically, by deleting it and recreating it. This is causing a problem, though. If I select a different chapter, the update_text()
function breaks as selected_page.get()
no longer works.
Is there any better way to update the contents of the page_drop
menu instead of deleting it and creating a new one? Or is there a better way to do what I'm trying to do in tkinter?
This is all the text I'm using:
from tkinter import *
def delete_text():
textbox.destroy()
def delete_pagedrop():
page_drop.destroy()
def update_text(event=None):
cur_page = selected_page.get()
cur_text = text_list[int(cur_page) - 1]
delete_text()
textbox = Label(root, width=80, height=3, text=cur_text, font=("Courier", 12))
textbox.grid(row=1, column=0)
def update_pages(event=None):
cur_chapter = selected_chapter.get()
cur_pages = pages_list[int(cur_chapter) - 1]
cur_page = cur_pages[0]
delete_pagedrop()
selected_page = StringVar()
selected_page.set(cur_page)
page_drop = OptionMenu(options_frame, selected_page, *cur_pages, command=update_text)
page_drop.grid(row=0, column=1)
if __name__ == "__main__":
# Create the window
chapter_list = ["1", "2", "3", "4", "5", "6"]
pages_list = [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"],
["10", "11", "12"], ["13", "14", "15"], ["16", "17", "18"]]
text_list = ["this is page 1", "this is page 2", "this is page 3",
"this is page 4", "this is page 5", "this is page 6",
"this is page 7", "this is page 8", "this is page 9",
"this is page 10", "this is page 11", "this is page 12",
"this is page 13", "this is page 14", "this is page 15",
"this is page 16", "this is page 17", "this is page 18"]
first_chapter = chapter_list[0]
first_pages = pages_list[0]
first_page = first_pages[0]
first_text = text_list[0]
root = Tk()
root.title("Book by chapters")
root.geometry("900x750")
options_frame = LabelFrame(root, padx=20, pady=20)
options_frame.grid(row=0, column=0, padx=10, pady=10, sticky="W")
selected_chapter = StringVar()
selected_chapter.set(first_chapter)
chapter_drop = OptionMenu(options_frame, selected_chapter, *chapter_list, command=update_pages)
chapter_drop.grid(row=0, column=0)
selected_page = StringVar()
selected_page.set(first_page)
page_drop = OptionMenu(options_frame, selected_page, *first_pages, command=update_text)
page_drop.grid(row=0, column=1)
textbox = Label(root, width=80, height=3, text=first_text, font=("Courier", 12))
textbox.grid(row=1, column=0)
# Run the GUI
root.mainloop()