Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/354.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Tkinter弹出命令_Python_Tkinter - Fatal编程技术网

Python Tkinter弹出命令

Python Tkinter弹出命令,python,tkinter,Python,Tkinter,我正在用Tkinter用Python制作一个文本编辑器,现在我正在制作新按钮,但当我按下该按钮时,它会在我单击“是”按钮之前删除所有内容。 代码如下: def new(): pop_up_new = Tk() lb_new = Label(pop_up_new, text="Are you sure to delete?") bt_new = Button(pop_up_new, text="Yes", command=text.delete(END, '1.0')) b

我正在用Tkinter用Python制作一个文本编辑器,现在我正在制作新按钮,但当我按下该按钮时,它会在我单击“是”按钮之前删除所有内容。 代码如下:

def new():
   pop_up_new = Tk()
   lb_new = Label(pop_up_new, text="Are you sure to delete?")
   bt_new = Button(pop_up_new, text="Yes", command=text.delete(END, '1.0'))
   bt_new_no = Button(pop_up_new, text="No", command=pop_up_new.destroy)
   lb_new.grid()
   bt_new.grid(row =1 , column = 0, sticky = W)
   bt_new_no.grid(row = 1, column = 1, sticky = W)


text = Text(window)
text.pack()

menubar = Menu(window)
filemenu = Menu(menubar, tearoff = 1)
filemenu.add_command(label="Open")
filemenu.add_command(label="Save")
filemenu.add_command(label="New", command=new)
filemenu.add_separator()
filemenu.add_command(label="Exit")
menubar.add_cascade(label="File", menu=filemenu)
window.config(menu=menubar)

在以下代码中,
text.delete()
实际上是在您尝试将其作为
按钮
对象的命令传递时调用的:

Button(pop_up_new, text="Yes", command=text.delete(END, '1.0'))
由于删除没有明显需要的参数,因此可以轻松使用lambda函数:

..., command=lambda : text.delete(END, '1.0'))
它创建了一个调用
text.delete()
的函数,并将此新函数作为
命令的值传递

或者,您可以定义自己的函数并将其作为命令传递:

def delete_text():
    text.delete(END, '1.0')


..., command=delete_text))

在这两种情况下,引用全局变量<代码>文本<代码>,因此如果可能的话,您应该考虑重构代码以使用类。

可能的副本与lambda一起工作!谢谢大家!@优生优生:没问题。你是新来的,所以你可能想退房。您还应该查看fhdrsdg发现的问题的公认答案,因为它比我上面的解释更好。