簡體   English   中英

GUI-tkinter制作按鈕

[英]GUI - tkinter Making a button

我要創建一個按鈕,該按鈕將允許用戶瀏覽並選擇文件並將選擇項分配給變量,這就是我所擁有的,我知道這是錯誤的,但是我似乎無法獲得有用的東西,請給我提示改善,謝謝。

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()

現在,這將打開文件對話框,但在程序運行后即會打開,我希望它僅在按下瀏覽按鈕后才運行,我該怎么做才能解決此問題?

您需要修復導入, 強烈建議對GUI使用OOP。

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() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM