Python 使用 TKinter 创建浏览按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16798937/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 23:42:22  来源:igfitidea点击:

Creating a Browse Button with TKinter

pythontkinter

提问by user2386081

I'm writing some code where the user needs to be able to select a file that the program will run on. I have created a browse button that allows the user to select a file but when you hit 'okay' the rest of the program doesn't realize that there has been an input. The file name should also automatically be entered in he browse bar after the file has been selected. Any suggestions?

我正在编写一些代码,用户需要在其中选择程序将在其上运行的文件。我创建了一个浏览按钮,允许用户选择一个文件,但是当你点击“好的”时,程序的其余部分没有意识到有一个输入。选择文件后,还应在浏览栏中自动输入文件名。有什么建议?

from Tkinter import *

class Window:       

def __init__(self, master):     

    #Browse Bar
    csvfile=Label(root, text="File").grid(row=1, column=0)
    bar=Entry(master).grid(row=1, column=1) 

    #Buttons  
    y=7
    self.cbutton= Button(root, text="OK", command=master.destroy)       #closes window
    y+=1
    self.cbutton.grid(row=10, column=3, sticky = W + E)
    self.bbutton= Button(root, text="Browse", command=self.browsecsv)
    self.bbutton.grid(row=1, column=3)

#-------------------------------------------------------------------------------------#
def browsecsv(self):
    from tkFileDialog import askopenfilename

    Tk().withdraw() 
    filename = askopenfilename()

#-------------------------------------------------------------------------------------#
import csv

with open('filename', 'rb') as csvfile:
    logreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    rownum=0

    for row in logreader:    
        NumColumns = len(row)        
        rownum += 1

    Matrix = [[0 for x in xrange(NumColumns)] for x in xrange(rownum)] 

csvfile.close()


root = Tk()
window=Window(root)
root.mainloop()  

回答by elactic

filename = askopenfilename()is only known in this scope, you have to return it or use it in any way.

filename = askopenfilename()仅在此范围内已知,您必须返回它或以任何方式使用它。

See this sitefor more examples:

有关更多示例,请参阅此站点

    Tkinter.Button(self, text='Browse', command=self.askopenfile)

...

...

    def askopenfile(self):
        return tkFileDialog.askopenfile(mode='r', **self.file_opt)


EDIT

编辑

Bryan Oakley is right of course! That is what I meant when i said "use it in any way" ;) At one point you choose a filename, at anoter you simply use filename.

布莱恩奥克利当然是对的!这就是我说“以任何方式使用它”时的意思;) 有一次您选择一个文件名,另一次您只需使用filename.

How about this?

这个怎么样?

from Tkinter import *
import csv

class Window:       
def __init__(self, master):     
    self.filename=""
    csvfile=Label(root, text="File").grid(row=1, column=0)
    bar=Entry(master).grid(row=1, column=1) 

    #Buttons  
    y=7
    self.cbutton= Button(root, text="OK", command=self.process_csv)
    y+=1
    self.cbutton.grid(row=10, column=3, sticky = W + E)
    self.bbutton= Button(root, text="Browse", command=self.browsecsv)
    self.bbutton.grid(row=1, column=3)

def browsecsv(self):
    from tkFileDialog import askopenfilename

    Tk().withdraw() 
    self.filename = askopenfilename()

def process_csv(self):
    if self.filename:
        with open(self.filename, 'rb') as csvfile:
            logreader = csv.reader(csvfile, delimiter=',', quotechar='|')
            rownum=0

            for row in logreader:    
                NumColumns = len(row)        
                rownum += 1

            Matrix = [[0 for x in xrange(NumColumns)] for x in xrange(rownum)] 

root = Tk()
window=Window(root)
root.mainloop()  

There is still a lot to dowith that, but at least you don't try to open a file before having determined its name.

还有很多事情要做,但至少在确定文件名称之前不要尝试打开文件。

回答by abhishekgarg

you can also use tkFileDialog..

你也可以使用 tkFileDialog ..

import Tkinter,tkFileDialog

root = Tkinter.Tk()
file = tkFileDialog.askopenfile(parent=root,mode='rb',title='Choose a file')
if file != None:
    data = file.read()
    file.close()
    print "I got %d bytes from this file." % len(data)

回答by Bryan Oakley

The root of the problem is that you're trying to process the file before the user has the chance to pick a file.

问题的根源在于您试图在用户有机会选择文件之前处理文件。

You need to put the block of code beginning with with open('filename', 'rb') as csvfile:in a function, then call the function as a result of the user pressing the button. For example, you could call it from within the browsecsvfunction.

您需要with open('filename', 'rb') as csvfile:将以开头的代码块放在一个函数中,然后在用户按下按钮时调用该函数。例如,您可以从browsecsv函数内部调用它。

Also, you don't need csv.close(), that comes for free when using the withstatement.

此外,您不需要csv.close(), 使用with语句时免费提供。

回答by Sandun Gunasekara

I have edited above code to use in python 3.6. Only package name changes

我已经编辑了上面的代码以在 python 3.6 中使用。仅包名称更改

    import tkinter
    from tkinter import filedialog
    file = filedialog.askopenfile(parent=root,mode='rb',title='Choose a file')
    if file != None:
        data = file.read()
        file.close()
        print("I got %d bytes from this file." % len(data))

回答by Iftikhar humayun

# importing tkinter and tkinter.ttk 
# and all their functions and classes 
from tkinter import * 
from tkinter.ttk import *

# importing askopenfile function 
# from class filedialog 
from tkinter.filedialog import askopenfile 

root = Tk() 
root.geometry('200x100') 

# This function will be used to open 
# file in read mode and only Python files 
# will be opened 
def open_file(): 
    file = askopenfile(mode ='r', filetypes =[('Python Files', '*.docx')]) 
    if file is not None: 
        content = file.read() 
        print(content) 

btn = Button(root, text ='Open', command = lambda:open_file()) 
btn.pack(side = TOP, pady = 10) 

mainloop()