GUI - tkinter制作一个按钮

时间:2014-05-26 23:14:58

标签: python user-interface tkinter

我想创建一个按钮,允许用户浏览并选择一个文件并将选择分配给变量,这就是我所拥有的,我知道这是错误的,但我似乎无法得到一些有用的东西,请给我提示改进,谢谢。

import tkinter

#Window
window = tkinter.Tk()
window.title("Title")
window.geometry("300x400")

#Label
fileSelectLBL = tkinter.Label(window, text="Please select your file:")
fileSelectLBL.pack()
#Button
filename = tkinter.Button(window, text="Browse", command = askopenfilename( filetypes = (("Text Files","*.txt"))))
filename.pack()

#Main Loop
windowindow.mainloop()

运行时出现此错误:

    filename = Button(window, text="Browse", command = window.load_file, width = 10)
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1886, in __getattr__
    return getattr(self.tk, attr)
AttributeError: 'tkapp' object has no attribute 'load_file'

点击按钮时出现此错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "/usr/lib/python3.4/idlelib/run.py", line 121, in main
    seq, request = rpc.request_queue.get(block=True, timeout=0.05)
  File "/usr/lib/python3.4/queue.py", line 175, in get
    raise Empty
queue.Empty

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/lib/python3.4/tkinter/__init__.py", line 1490, in __call__
    return self.func(*args)
TypeError: load_file() missing 1 required positional argument: 'self'

我已将其更新为:

import tkinter
from tkinter import *
from tkinter.filedialog import askopenfilename
from tkinter.messagebox import showerror
from tkinter import filedialog
#Window
window = tkinter.Tk()
window.title("Title")
window.geometry("300x400")
def load_file():
    fname = askopenfilename(filetypes=(("Template files", "*.tplate"),
                                       ("HTML files", "*.html;*.htm"),
                                       ("All files", "*.*") ))
    if fname:
        try:
            print("""here it comes: self.settings["template"].set(fname)""")
        except:                     # <- naked except is a bad idea
            showerror("Open Source File", "Failed to read file\n'%s'" % fname)
        return


window.button = Button(window, text="Browse", command=load_file(), width=10)

#Label
fileSelectLBL = tkinter.Label(window, text="Please select your file:")
fileSelectLBL.pack()

#Button
def load_file(self):
    fname = askopenfilename(filetypes=(("Text files", "*.txt"),
                                       ("All files", "*.*") ))
filename = tkinter.Button(window, text="Browse", command = load_file)
filename.pack()

filename = Button(window, text="Browse", command = window.load_file, width = 10)


#Main Loop
windowindow.mainloop()

现在打开文件对话框,但程序运行后会立即打开,我希望它只在按下浏览按钮时运行,我该怎么办才能解决这个问题?

1 个答案:

答案 0 :(得分:0)

您需要修复导入,并建议 HIGHLY 将OOP与GUI结合使用。

from tkinter import *
from tkinter.filedialog import askopenfilename

class Example(Frame):
    def __init__(self, parent):
        Frame.__init__(self, parent)   

        self.parent = parent        
        self.initUI()

    def initUI(self):

        self.parent.title("File dialog")

        #Label
        self.fileSelectLBL = Label(self, text="Please select your file:")
        self.fileSelectLBL.pack()

        #Button
        self.filename = Button(self, text="Browse", command = self.load_file)
        self.filename.pack()

    def load_file(self, ftypes = None):
        ftypes = ftypes or (("Text Files","*.txt"))
        fl     = askopenfilename(filetypes = ftypes)

        if fl != '':
            print(fl)

def main():
    window = Tk()
    ex = Example(window)
    window.geometry("300x400")

    #Main Loop
    window.mainloop()

if __name__ == '__main__':
    main()