简体   繁体   中英

tkinter - open file with button and save filename to variable


I am trying to solve a problem that seems simple, but I cannot figure out how.
I want to create a simple program checking if a certain symbol exists in a text file:

  1. The program starts;
  2. The user clicks a button (inside the window, not in the menu);
  3. A dialog box appears;
  4. The user chooses a text file;
  5. A message box displays the result;
  6. The program closes.

Pretty straightforward, but I cannot find how to save the filename into a variable and then use it for the process. I read so many tutorials and I could not find a solution. Here is the code:

from tkinter import *
from tkinter import filedialog


def clicked():
    global filename
    filename = filedialog.askopenfile(filetypes=(("Word files","*.docx"),))


window = Tk()
window.geometry()
window.title("My App")
open_file_label = Label(window, text="Open your docx file here:", font=("Arial", 10), padx=5, pady=5)
open_file_label.grid(column=0, row=0)
open_file_button = Button(window, text="Click me", command=clicked, padx=5, pady=5)
open_file_button.grid(column=1, row=0)

window.mainloop()

filename is already a variable that contains the chosen file's contents. Just print(filename) and you'll get your data printed in console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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