Please help with if-Condition

Hello together,
i don’t understand the Condition in the if-Statement:

# -*- coding: iso-8859-1 -*-

import tkinter as tk
from tkinter import filedialog

def öffnen_und_anzeigen():
    # Datei auswählen
    datei = filedialog.askopenfilename(filetypes=[("Textdateien", "*.txt")])
    if datei:
        # Datei öffnen und lesen
        with open(datei, "r") as f:
            inhalt = f.read()

        # Neues Fenster zum Anzeigen erstellen
        fenster = tk.Toplevel()
        text_bereich = tk.Text(fenster)
        text_bereich.insert(tk.END, inhalt)
        text_bereich.pack()

# Hauptfenster erstellen
fenster = tk.Tk()
fenster.title("Datei auswählen und anzeigen")

# Button zum Öffnen der Datei
button = tk.Button(fenster, text="Datei öffnen", command=öffnen_und_anzeigen)
button.pack()

fenster.mainloop() 


Please try to explain.
Thank you,
Havefun

This:

datei = filedialog.askopenfilename(filetypes=[("Textdateien", "*.txt")])

prompts the user to select a file and stores the result in datei.

If the user cancelled the dialog box, the result will be an empty string.

This:

if datei:

checks whether or not the user selected a file.

If the user did select a file, datei won’t be an empty string, which the if statement will treat as true.

If the user didn’t select a file, but cancelled the dialog instead, datei will be an empty string, which the if statement will treat as false.

1 Like

Hello,

just a little feedback with your script. You really don’t need the following line since you already have imported tkinter as tk.

from tkinter import filedialog

Just prefix filedialog with tk wherever it is used and you should be fine. You’re already doing this with other tkinter names so it is not a stretch.

I also noticed that you have created two variables (a global and a local) with the same name. Although there shouldn’t by any name collision, you should still think of naming variables with distinct names. The variable in question is fenster.

Maybe:

hauptfenster = tk.Tk()

Thank you Matthew.
The Code is KI-generatet.
I expected:

if (datei =! “”) :
or so

I didn’t know that Python says the Condition is true, when “datei” is not empty.
Greetings
Havefun

Please try such suggestion before you post.

>>> import tkinter as tk
>>> tk.filedialog
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    tk.filedialog
AttributeError: module 'tkinter' has no attribute 'filedialog'
>>> 

Importing a module does not automatically import submodules, and tkinter does not do so. Importing a submodule does add its name to the module, but then the prefix is not needed.

>>> from tkinter import filedialog
>>> tk.filedialog
<module 'tkinter.filedialog' from 'C:\\Programs\\Python314\\Lib\\tkinter\\filedialog.py'>