0

我的 tkinter 应用程序的框架中有两个OptionMenu小部件。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页面应显示在屏幕上。

因此,当在第一OptionMenu个小部件中进行选择时,我需要更新第二OptionMenu个小部件的内容。我一直在使用update_pages()下面的函数来更新第二个小部件,基本上是通过删除它并重新创建它。但是,这会导致问题。如果我选择不同的章节,该update_text()功能将因selected_page.get()不再有效而中断。

有没有更好的方法来更新page_drop菜单的内容而不是删除它并创建一个新的?或者有没有更好的方法来做我想要在 tkinter 中做的事情?

这是我正在使用的所有文本:

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

0 回答 0