【问题标题】:How do I control file opening with Tkinter buttons?如何使用 Tkinter 按钮控制文件打开?
【发布时间】:2014-02-13 02:17:26
【问题描述】:

我想在我的 tkinter gui 中按下按钮打开一个文件。但是,声音文件在我的程序运行时播放(如立即运行)并且在按下按钮时不起作用。这是我的代码:

    ####Imports
    import os
    import sys
    from tkinter import *

    ####definitions
    def blackobj ():
        from os import startfile
        startfile ('simon_objection.mp3')

    ####Window
    mGui = Tk()
    mGui.geometry ('1280x720+100+50')
    mGui.title ('Gui App')
    mGui.configure(background='blue')

    ####Labels
    #Title
    wlabel = Label(text = "Welcome to the Ace Attorney Soundboard!", font = 'georgia',fg  ='white', bg = 'blue').place(x=0,y=0)
    objectionheader = Label (text = 'Objections:', font = 'georgia', fg = 'white', bg = 'blue',).place (x=0,y=45)

    ####Buttons
    objblackquill = Button (mGui, text = 'Blackquill', font = 'georgia', command =blackobj()).place (x=0,y=75)

    mGui.mainloop()

我的代码是否有错误,或者我是否需要添加其他内容才能在按下按钮而不是脚本运行时发出声音?

谢谢

【问题讨论】:

    标签: python button user-interface tkinter


    【解决方案1】:
    objblackquill = Button (mGui, text = 'Blackquill', font = 'georgia', command =blackobj()).place (x=0,y=75)
    

    您的问题与上述行有关。当 Python 读取您的代码时,它会看到 blackobj(),它会将其解释为有效的函数调用。所以,它执行它。


    要解决此问题,您可以使用 lambda 在其自己的函数中“隐藏”对 blackobj 的调用:

    objblackquill = Button (..., command=lambda: blackobj()).place (x=0,y=75)
    

    但是,由于您没有传递 blackobj 任何参数,因此更好的解决方案是删除括号:

    objblackquill = Button (..., command=blackobj).place (x=0,y=75)
    

    另外,tkinter.<widget>.place 总是返回 None,因此应该在自己的行上调用。

    换句话说,每一行都是这样写的:

    wlabel = Label(...).place(x=0,y=0)
    

    应该这样写:

    wlabel = Label(...)
    wlabel.place(x=0,y=0)
    

    【讨论】:

    • 除非您不再需要对您的对象做任何事情,在这种情况下,不要将它们分配给变量。我一直使用Labels 为我的Entry 字段执行此操作。 date = StringVar(); e_date=ttk.Entry(root,textvariable=date); e_date.grid(row=1,column=2); ttk.Label(root,text="Date:").grid(row=1,column=1
    • 非常感谢!这解决了我遇到的问题,非常感谢您提供额外的建议!
    猜你喜欢
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多