首页 > 解决方案 > 命令只做一个功能

问题描述

我正在使用 tkinter 创建一个 gui,我正在尝试让我的代码删除按钮,但是“命令”似乎不能执行多个功能

label1 = tkinter.Button(root, text="hello world", padx=50, pady=50, command=hello_world, fg="black", bg="yellow")
label2 = tkinter.Button(root, text="hello there", padx=50, pady=50, command=hello_there, fg="black", bg="green")
base = tkinter.Button(root, text="Return", padx=50, pady=50, command=label2.destroy and label1.destroy, fg="black", bg="red")

当我尝试执行命令时,实际上只执行了最后一个命令

标签: pythontkinter

解决方案


您可以简单地定义一个运行这两个函数的中间函数。请看下面的一个小例子

import tkinter as tk

def func1():
    print("Executed function 1")

def func2():
    print("Executed function 2")

def combined_func():
    func1()
    func2()

root = tk.Tk()
btn = tk.Button(root, text='My button', command=combined_func)
btn.pack()

root.mainloop()

如果您不想创建中间函数,还可以使用包含需要运行的每个函数的元组来定义 lambda。看起来像这样

tk.Button(root, text='My button', command=lambda: (func1(), func2()))

推荐阅读