Tkinter - 运行时错误:超过最大递归深度

7
我周一开始学习Python编程,很喜欢它。但是我在尝试理解如何在tkinter菜单之间切换时避免递归方面遇到了困难!我相信这是一个非常基本的问题,感谢您容忍我对这个主题的无知,但我一直找不到答案。
目前我正在使用的模式最终会导致错误:RuntimeError: maximum recursion depth exceeded while calling a Python object
下面是我目前正在使用的代码。更新:下面的代码现在是完整的、孤立的副本,重现了我所面临的问题! :D
from tkinter import *

def mainmenu():
    global frame, root

    frame.destroy()

    frame = Frame()
    frame.pack()

    button1 = Button(frame, text="anothermenulikethis", command = anothermenulikethis)
    button2 = Button(frame, text="anothermenulikethis", command = anothermenulikethis)
    button3 = Button(frame, text="mainmenu", command = mainmenu)

    button1.pack(side=LEFT)
    button2.pack(side=LEFT)
    button3.pack(side=LEFT)

    root.mainloop()

def anothermenulikethis():
    global frame, root

    frame.destroy()

    frame = Frame()
    frame.pack()

    button1 = Button(frame, text="mainmenu", command = mainmenu)
    button2 = Button(frame, text="mainmenu", command = mainmenu)
    button3 = Button(frame, text="anothermenulikethis", command = anothermenulikethis)

    button1.pack(side=LEFT)
    button2.pack(side=LEFT)
    button3.pack(side=LEFT)

    root.mainloop()

root = Tk()
root.title("Recursive Menu Problem Isolation")
root.geometry("1200x600")
frame = Frame()

mainmenu()

这一切都正常运作,直到它达到最大递归深度而产生必然的故障。如果有人能建议更好的处理方式,或者提供一个示例来说明更好的解决方案,我非常愿意学习。

附言:我尝试过增加递归深度,但我认为这是对我的方法固有问题的贫穷解决方案。

提前感谢大家。

按照要求,这里是回溯信息:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/tkinter/__init__.py", line 1399, in __call__
    return self.func(*args)
  File "/Users/diligentstudent/Desktop/menutest.py", line 11, in mainmenu
    button1 = Button(frame, text="anothermenulikethis", command = anothermenulikethis)
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/tkinter/__init__.py", line 2028, in __init__
    Widget.__init__(self, master, 'button', cnf, kw)
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/tkinter/__init__.py", line 1958, in __init__
    (widgetName, self._w) + extra + self._options(cnf))
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/tkinter/__init__.py", line 1043, in _options
    v = self._register(v)
  File "/Library/Frameworks/Python.framework/Versions/3.2/lib/python3.2/tkinter/__init__.py", line 1079, in _register
    f = CallWrapper(func, subst, self).__call__
RuntimeError: maximum recursion depth exceeded

你能贴出堆栈跟踪吗?需要知道是哪个函数导致了递归深度异常。 - Anthony Kong
我已经按要求发布了回溯信息。 :) - A Diligent Student
2个回答

12

只需要一个mainloop()就可以处理tkinter GUI。

话虽如此,我认为你只需要一个类结构的示例:

from tkinter import Tk,Button

class Application(Tk):

    def say_hi(self):
        print('Hello world?!')

    def close_app(self):
        self.destroy()

    def create_Widgets(self):
        self.quitButton = Button(self, width=12, text='Quit', bg='tan',
                    command=self.close_app)
        self.quitButton.grid(row=0, column=0, padx=8, pady=8)

        self.helloButton = Button(self, width=12, text='Hello',
                    command=self.say_hi)
        self.helloButton.grid(row=0, column=1, padx=8, pady=8)

    def __init__(self):
        Tk.__init__(self)
        self.title('Hello world!')
        self.create_Widgets()

app = Application()
app.mainloop()
为了避免与其他模块可能发生的冲突,有些人更喜欢像这样导入(清楚地说明一切的来源):

为了避免与其他模块可能发生的冲突,有些人更喜欢像这样导入(清楚地说明一切的来源):

import tkinter as tk

class Application(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title('Hello world!')

        self.quitButton = tk.Button(self, width=12, text='Quit', bg='tan',
                    command=self.close_app)
        self.quitButton.grid(row=0, column=0, padx=8, pady=8)

        self.helloButton = tk.Button(self, width=12, text='Hello',
                    command=self.say_hi)
        self.helloButton.grid(row=0, column=1, padx=8, pady=8)

    def say_hi(self):
        print('Hello world?!')

    def close_app(self):
        self.destroy()

app = Application()
app.mainloop()

正如您所看到的,创建小部件可以轻松地在__init__中完成。


我决定基于我过去一个月学到的知识制作更实用/教育性的示例。在这样做时,我有了一些启示:并非所有东西都需要类中的self前缀!对于tkinter类而言尤其如此,因为您不会将其作为主程序中的对象来操作。当您稍后要在方法中使用某些内容时,通常需要self前缀。前面的示例显示了任何内容(如按钮)都可以接收self前缀,即使完全不必要也是如此。

该示例将展示以下一些内容:

• 在同一GUI中,只要它们不共享主控件,就可以同时使用pack()grid()

• 可以使文本小部件在字体大小更改时不扩展。

• 如何在选定的文本上切换粗体标记。

• 如何真正将GUI居中于屏幕(更多信息在此处)

• 如何使Toplevel窗口相对于主窗口出现在相同位置。

• 防止销毁Toplevel窗口的两种方法,因此只需要创建一次。

• 使ctrl+a(全选)正常工作。

import tkinter as tk
import tkFont

class Application(tk.Tk):

    def __init__(self):
        tk.Tk.__init__(self)
        self.title('T-Pad')

    # Menubar

        menubar = tk.Menu(self)

        filemenu = tk.Menu(menubar, tearoff=0)
        filemenu.add_command(label="Exit", command=self.close_app)
        menubar.add_cascade(label="File", menu=filemenu)

        formatmenu = tk.Menu(menubar, tearoff=0)
        formatmenu.add_command(label="Font", command=self.show_sizeWin)
        menubar.add_cascade(label="Format", menu=formatmenu)

        self.config(menu=menubar)

    # Bold Button

        boldButton = tk.Button(self, width=12, text='Bold',
                                command=self.make_bold)
        boldButton.pack()

    # Text widget, its font and frame

        self.defaultFont = tkFont.Font(name="defFont")

        textFrame = tk.Frame(self, borderwidth=1, relief="sunken",
                             width=600, height=600)

        textFrame.grid_propagate(False) # ensures a consistent GUI size
        textFrame.pack(side="bottom", fill="both", expand=True)


        self.mText = tk.Text(textFrame, width=48, height=24, wrap='word',
                            font="defFont")
        self.mText.grid(row=0, column=0, sticky="nsew")

    # Scrollbar and config

        tScrollbar = tk.Scrollbar(textFrame, command=self.mText.yview)
        tScrollbar.grid(row=0, column=1, sticky='nsew', pady=1)

        self.mText.config(yscrollcommand=tScrollbar.set)

    # Stretchable

        textFrame.grid_rowconfigure(0, weight=1)
        textFrame.grid_columnconfigure(0, weight=1)

    # Bold Tag

        self.bold_font = tkFont.Font(self.mText, self.mText.cget("font"))
        self.bold_font.configure(weight="bold")
        self.mText.tag_configure("bt", font=self.bold_font)

    # Center main window

        self.update_idletasks()

        xp = (self.winfo_screenwidth() / 2) - (self.winfo_width() / 2) - 8
        yp = (self.winfo_screenheight() / 2) - (self.winfo_height() / 2) - 30
        self.geometry('{0}x{1}+{2}+{3}'.format(self.winfo_width(), self.winfo_height(),
                                                                                xp, yp))

    # Font Size Window (notice that self.sizeWin is given an alias)

        sizeWin = self.sizeWin = tk.Toplevel(self, bd=4, relief='ridge')

        self.sizeList = tk.Listbox(sizeWin, width=10, height=17, bd=4,
                                font=("Times", "16"), relief='sunken')

        self.sizeList.grid()

        doneButton = tk.Button(sizeWin, text='Done', command=sizeWin.withdraw)
        doneButton.grid()

        for num in range(8,25):
            self.sizeList.insert('end', num)

        sizeWin.withdraw()

        sizeWin.overrideredirect(True) # No outerframe!
        # Below is another way to prevent a TopLevel window from being destroyed.
        # sizeWin.protocol("WM_DELETE_WINDOW", self.callback)

    # Bindings
        # Double click a font size in the Listbox
        self.sizeList.bind("<Double-Button-1>", self.choose_size)
        self.bind_class("Text", "<Control-a>", self.select_all)

##    def callback(self):
##        self.sizeWin.withdraw()

    def select_all(self, event):
        self.mText.tag_add("sel","1.0","end-1c")

    def choose_size(self, event=None):
        size_retrieved = self.sizeList.get('active')
        self.defaultFont.configure(size=size_retrieved)
        self.bold_font.configure(size=size_retrieved)

    def show_sizeWin(self):
        self.sizeWin.deiconify()
        xpos = self.winfo_rootx() - self.sizeWin.winfo_width() - 8
        ypos = self.winfo_rooty()
        self.sizeWin.geometry('{0}x{1}+{2}+{3}'.format(self.sizeWin.winfo_width(),
                                                self.sizeWin.winfo_height(), xpos, ypos))

    def make_bold(self):
        try:
            current_tags = self.mText.tag_names("sel.first")
            if "bt" in current_tags:
                self.mText.tag_remove("bt", "sel.first", "sel.last")
            else:
                self.mText.tag_add("bt", "sel.first", "sel.last")
        except tk.TclError:
            pass

    def close_app(self):
        self.destroy()

app = Application()
app.mainloop()

哦哦哦哦哦!是的,那正是我在寻找的模式!非常感谢你! :D - A Diligent Student
@ADiligentStudent 不客气!我添加了一个稍微修改过的版本。 - Honest Abe
@ADiligentStudent 我已经再次更新了。这次加上了一个实际的例子,包括一个顶层(次要)窗口,似乎是你想做的。 - Honest Abe
@HonestAbe 很棒的答案,非常详细。+1 - George

0
与此问题有关的其他人需要注意:您的按钮命令可能没有正确的缩进级别! 在深入研究之前,请检查它是否与其他类方法内联。 我自己不久前也遇到了这个问题,重新检查我的缩进就解决了一切。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接