0


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

1 Answers1

0

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

Simo Todorov
  • 26
  • 1
  • 6
  • Yes, but I should put all of the script logic in the def code, which will seem a bit weird. I was thinking of a way to use the filename variable not only in scope of that function, but it does not work. Thanks, I will see what will happen. – Boris Kondev Dec 16 '19 at 14:56
  • in that case you should create the variable filename outside of the method, right under the imports, and then assign the chosen file to it just like you have right now. Then you can use that variable outside of the method – Simo Todorov Dec 17 '19 at 13:32
  • @SimoTodorov ***"create the variable filename outside of the method"***: The variable `filename` is already defined as `global`. Therefore you can access it from everywhere. – stovfl Dec 17 '19 at 13:41