简体   繁体   English

使用 TKinter 创建浏览按钮

[英]Creating a Browse Button with TKinter

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

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:
    data = file.read()
    file.close()
    print "I got %d bytes from this file." % len(data)

filename = askopenfilename() is only known in this scope, you have to return it or use it in any way. filename = askopenfilename()仅在此范围内已知,您必须返回它或以任何方式使用它。

See this site for 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 do with that, but at least you don't try to open a file before having determined its name.还有很多事情要做,但至少在确定文件名称之前不要尝试打开文件。

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

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.您需要with open('filename', 'rb') as csvfile:开头的代码块with open('filename', 'rb') as csvfile:放在函数中,然后作为用户按下按钮的结果调用该函数。 For example, you could call it from within the browsecsv function.例如,您可以从browsecsv函数中调用它。

Also, you don't need csv.close() , that comes for free when using the with statement.此外,您不需要csv.close() ,它在使用with语句时免费with

I have edited above code to use in python 3.6.我已经编辑了上面的代码以在 python 3.6 中使用。 Only package name changes仅包名称更改

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM