pythontkintersaveexitsavefiledialog

Python: filedialog.asksaveasfilename() exits accidentally


Recently I'm learning PyQt5 and Tkinter, and I'm implementing a function that saving text as a txt to the address I designated. The codes are here(part of the hole application):

import tkinter.messagebox

from PyQt5.QtWidgets import QApplication, QMainWindow
from MainWindow import Ui_MainWindow
from PyQt5 import QtCore
import BackgroundClient
import threading
import re
from tkinter import filedialog, dialog
import tkinter as tk

class MyMainForm(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainForm, self).__init__(parent)
        self.setupUi(self)
        self.save_txt_button.clicked.connect(self.generate_txt)
        
    def generate_txt(self):
        root = tk.Tk()
        root.withdraw()
        file_path = filedialog.asksaveasfilename()
        if file_path is not None:
            file_text = str(self.conversation_bowser.toPlainText())
            with open(file=file_path, mode='a+', encoding='gbk') as file:
                file.write(file_text)
            # tkinter.messagebox.
            tkinter.messagebox.showinfo("tip", "successful")
        else:
            print("empty file")
            return

The codes acted like the picture followed: enter image description here. When I input the address of the file and click 保存(which means "Save"), the file can be saved successfully. However, when I click 取消(which means "Cancel"), no matter the address is empty or not, the application exits with code -1073740791 (0xC0000409).

So what could cause the problem? Is there any way to solve this problem? Thanks.


Solution

  • If you click cancel on the filedialog, your file_path variable will be equal to '' (the empty string) and not None.

    Thus, you're always running the if statement as True, even if there's no filename to target.

    EDIT: The empty string evaluates to False (see Python docs on truth value testing) so you could use just if file_path to test if you can save the file.