Tkinter 按钮不执行命令

Tkinter Button does not execute command

我正在尝试创建一个从用户计算机打开本地文件的按钮。我设置了按钮,打开文件的功能非常简单。单击实际按钮时,实际上什么也没有发生。预期的结果应该是打开一个显示本地文件的框。

到目前为止,这是我的程序:

from tkinter import *
import tkinter.filedialog

gui = Tk(className='musicAi')
gui.geometry("500x500")


def UploadAction(event=None):
    filename = filedialog.askopenfilename()
    print('Selected:', filename)

# create button
importMusicButton = Button(gui, text='Import Music', command = UploadAction, width=40, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa')
linkAccountButton = Button(gui, text='Link Account', width=40, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa')
settingsButton = Button(gui, text='Settings', width=40, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa')
helpButton = Button(gui, text='Help', width=40, height=3, bg='#0052cc', fg='#ffffff', activebackground='#0052cc', activeforeground='#aaffaa')
# add button to gui window
importMusicButton.pack()
linkAccountButton.pack()
settingsButton.pack()
helpButton.pack()


gui.mainloop()

由于您使用import tkinter.filedialog导入filedialog,您需要使用tkinter.filedialog.askopenfilename()来执行askopenfilename()

import tkinter.filedialog 更改为 from tkinter import filedialogimport tkinter.filedialog as filedialog

由于您在上传函数中使用了事件对象作为参数,因此请使用绑定方法。

ImportMusicButton.bind(<"Button-1">, lambda:UploadAction())

在您的 UploadAction(event = None) 中,删除事件参数的默认值。应该是

def UploadAction(event):
    code goes here...

我有一个完美的选择给你。

而不是使用: import tkinter.filedialog 你可以用更好的东西。

使用: from tkinter.filedialog import *

然后您可以从 filename = filedialog.askopenfile() 中删除 filedialog

改为: filename = askopenfile() :)