gpt4 book ai didi

Python tkinter.ttk 组合框在退出时抛出异常

转载 作者:行者123 更新时间:2023-11-28 22:56:33 26 4
gpt4 key购买 nike

在我的 Python 3.3 代码中,我使用了 ttk 库中的一些组合框,它们运行良好,但如果我使用它们中的任何一个,当我使用 X 按钮关闭窗口时出现异常。这是一个例子:

from tkinter import Tk,Label,Button
from tkinter import ttk
from tkinter.ttk import Combobox

def cbox_do(event):
'Used for cbox.'
clabel.config(text=cbox.get())

a = Tk()
cbox = Combobox(a, value=('Luke','Biggs','Wedge'), takefocus=0)
cbox.bind("<<ComboboxSelected>>", cbox_do)
cbox.pack()
clabel = Label(a)
clabel.pack()
a.mainloop()

如果你在没有选择值的情况下关闭它,一切都很好,但在选择一个值后尝试关闭它,它退出但在 python 命令行中打印以下错误:

can't invoke "winfo" command:  application has been destroyed
while executing
"winfo exists $w"
(procedure "ttk::entry::AutoScroll" line 3)
invoked from within
"ttk::entry::AutoScroll .41024560"
(in namespace inscope "::" script line 1)
invoked from within
"::namespace inscope :: {ttk::entry::AutoScroll .41024560}"
("uplevel" body line 1)
invoked from within
"uplevel #0 $Repeat(script)"
(procedure "ttk::Repeat" line 3)
invoked from within
"ttk::Repeat"
("after" script)

我该如何解决?如果您能提供任何帮助,我将不胜感激。

更新 1:我的 Python 版本是 v3.3,我使用捆绑的 Tcl/Tk 和 Tkinter。我尝试了 x86 和 x64 版本。

更新 2:仅当我从命令行运行脚本时才会抛出异常。它不会出现在 Idle 中。

最佳答案

这是ttk中使用的Tcl/Tk绑定(bind)代码的问题。

在典型的 python Tkinter 安装中,tcl/tk8.5/ttk/entry.tcl 文件中的注释暗示了这个问题:

## AutoScroll
# Called repeatedly when the mouse is outside an entry window
# with Button 1 down. Scroll the window left or right,
# depending on where the mouse is, and extend the selection
# according to the current selection mode.
#
# TODO: AutoScroll should repeat faster (50ms) than normal autorepeat.
# TODO: Need a way for Repeat scripts to cancel themselves.

基本上,在最后一个窗口关闭并且 Tk 完成后,使用 after 的延迟调用不会被取消并且无法再完成,因为过程/函数“winfo”不再存在。当你运行 IDLE 时,仍然有一个窗口,所以 Tk 没有完成,错误也没有显示出来。

您可以通过绑定(bind) WM_DELETE_WINDOW 消息来解决此问题,这会停止重复计时器。其代码将是(在 Tcl/Tk 中):

proc shutdown_ttk_repeat {args} {
::ttk::CancelRepeat
}
wm protocol . WM_DELETE_WINDOW shutdown_ttk_repeat

对于 Tkinter,它应该以类似的方式工作:

from tkinter import Tk,Label,Button
from tkinter import ttk
from tkinter.ttk import Combobox

def cbox_do(event):
'Used for cbox.'
clabel.config(text=cbox.get())

a = Tk()
cbox = Combobox(a, value=('Luke','Biggs','Wedge'), takefocus=0)
cbox.bind("<<ComboboxSelected>>", cbox_do)
cbox.pack()
clabel = Label(a)
clabel.pack()

def shutdown_ttk_repeat():
a.eval('::ttk::CancelRepeat')
a.destroy()

a.protocol("WM_DELETE_WINDOW", shutdown_ttk_repeat)
a.mainloop()

关于Python tkinter.ttk 组合框在退出时抛出异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15448914/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com