如何在不自动打开 Tkinter 的情况下调用函数命令
How do i call a command on a function without automatically opening on Tkinter
我正在尝试为每个按钮添加一个功能,但是当我这样做时,该功能会立即打开,而无需我按下菜单中的按钮。
你好,我是编程新手,我正在尝试学习一些关于为记事本创建菜单的基础知识,到目前为止我已经学会了如何创建菜单和其中的按钮,我正在尝试为每个按钮添加一个功能,但是当我这样做时,该功能会立即打开而无需我按下菜单中的按钮,到目前为止唯一有效的是尝试 lambda 函数,但我希望能够编写该函数无需在 lambda 函数之后为该函数编写整个代码。
from tkinter import Tk, scrolledtext, Menu, filedialog
from tkinter.scrolledtext import ScrolledText
from tkinter import*
#Root main window
root = Tk(className=" Text Editor")
textarea = ScrolledText(root, width=80, height=100)
textarea.pack()
# Menu options
menu = Menu(root)
root.config(menu=menu)
filename = Menu(menu)
edicion = Menu(menu)
# Funciones
def open_file ():
file = filedialog.askopenfiles(parent=root, mode='rb', title="Select a file")
if file != None:
contenidos = file.read()
textarea.insert('1.0', contenidos)
file.close
menu.add_cascade(label="File", menu=filename)
filename.add_command(label="New")
filename.add_command(label="Open", command= open_file)
filename.add_command(label="Save")
filename.add_separator()
filename.add_command(label="Exit")
menu.add_cascade(label="Editar", menu=edicion)
edicion.add_command(label="Cortar")
edicion.add_command(label="Pegar")
edicion.add_command(label="Copiar")
textarea.pack()
root.mainloop()
这一行:
filename.add_command(label="Open", command= open_file())
您不希望在您的命令后有额外的 ()
,那将调用您的函数。不尝试:
filename.add_command(label="Open", command= open_file)
我正在尝试为每个按钮添加一个功能,但是当我这样做时,该功能会立即打开,而无需我按下菜单中的按钮。
你好,我是编程新手,我正在尝试学习一些关于为记事本创建菜单的基础知识,到目前为止我已经学会了如何创建菜单和其中的按钮,我正在尝试为每个按钮添加一个功能,但是当我这样做时,该功能会立即打开而无需我按下菜单中的按钮,到目前为止唯一有效的是尝试 lambda 函数,但我希望能够编写该函数无需在 lambda 函数之后为该函数编写整个代码。
from tkinter import Tk, scrolledtext, Menu, filedialog
from tkinter.scrolledtext import ScrolledText
from tkinter import*
#Root main window
root = Tk(className=" Text Editor")
textarea = ScrolledText(root, width=80, height=100)
textarea.pack()
# Menu options
menu = Menu(root)
root.config(menu=menu)
filename = Menu(menu)
edicion = Menu(menu)
# Funciones
def open_file ():
file = filedialog.askopenfiles(parent=root, mode='rb', title="Select a file")
if file != None:
contenidos = file.read()
textarea.insert('1.0', contenidos)
file.close
menu.add_cascade(label="File", menu=filename)
filename.add_command(label="New")
filename.add_command(label="Open", command= open_file)
filename.add_command(label="Save")
filename.add_separator()
filename.add_command(label="Exit")
menu.add_cascade(label="Editar", menu=edicion)
edicion.add_command(label="Cortar")
edicion.add_command(label="Pegar")
edicion.add_command(label="Copiar")
textarea.pack()
root.mainloop()
这一行:
filename.add_command(label="Open", command= open_file())
您不希望在您的命令后有额外的 ()
,那将调用您的函数。不尝试:
filename.add_command(label="Open", command= open_file)