0

我在 Python 上创建了两个函数:

  • 一个打开一个新窗口:new_window()
  • 另一个在其上创建按钮:create_buttons('text displayed')

当我启动它们时,new_window 运行良好,但 create_button 显示 [无法调用“按钮”命令:应用程序已被破坏],就好像我的主窗口已被破坏......但我的窗口仍然打开!

... 你有什么主意吗 ??

import Tkinter

from Tkinter import *

def new_window():

   master = Tk()

def create_buttons(display):

   new_button= Button(master, text=display)

   new_button.pack()

new_window() ### OK, CREATES A WINDOW

create_buttons('text') ### DISPLAYS FOLLOWING BUG :

create_buttons('text')

TclError                                  Traceback (most recent call last)

/neurospin/grip/protocols/MRI/childrenDTIreading_Letarnec_2011/tools/data_mysql/<ipython console> in <module>()

/neurospin/grip/protocols/MRI/childrenDTIreading_Letarnec_2011/tools/data_mysql/<ipython console> in create_buttons(display)

/usr/lib/python2.6/lib-tk/Tkinter.pyc in __init__(self, master, cnf, **kw)
   2003             overrelief, state, width
   2004         """
-> 2005         Widget.__init__(self, master, 'button', cnf, kw)
   2006 
   2007     def tkButtonEnter(self, *dummy):

/usr/lib/python2.6/lib-tk/Tkinter.pyc in __init__(self, master, widgetName, cnf, kw, extra)
   1933                 del cnf[k]
   1934         self.tk.call(
-> 1935             (widgetName, self._w) + extra + self._options(cnf))
   1936         for k, v in classes:
   1937             k.configure(self, v)

TclError: can't invoke "button" command:  application has been destroyed
4

1 回答 1

1

正如 JFSebastian 所说,您需要使master变量可用于创建按钮的位置。一些这样做的代码可能如下所示:

from Tkinter import *

def new_window():
   return Tk()

def create_buttons(master, display):
   new_button = Button(master, text=display)
   new_button.pack()

master = new_window()
create_buttons(master, 'text')

这并不漂亮,但应该足以摆弄一下。如果代码变得严肃,最好将新窗口及其按钮包装到它自己的类中。

于 2013-02-07T11:39:02.150 回答