def save_file_cmd(puzzle_frame, parent):
"""
Input's save to file button click handler
puzzle_frame : The puzzle frame which it's puzzle will be saved to file
parent : The parent window of the puzzle_frame
This is used for showing the 'save as file' dialog so it can be showed on top of the window.
"""
# Check if puzzle frame has a valid input, and if not, ask the user if he's sure he wants to save the puzzle
lst = is_input_puzzle_valid(puzzle_frame)
if not lst:
if not messagebox.askokcancel("Input not valid",
"Input puzzle is not valid, are you sure to save it as a file?",
parent=parent):
return
# Open the 'save as file' dialog
file_name = filedialog.asksaveasfilename(title="Choose a file to save puzzle", parent=parent)
# Check if user has selected a file
if not file_name:
return
# Generate file's content
len_sqrt = int(math.sqrt(len(lst)))
file_lines = []
for i in range(0, len(lst), 3):
line_nums = []
for j in range(0, len_sqrt):
line_nums.append(str(lst[i + j]))
file_lines.append(' '.join(line_nums))
try:
with open(file_name, 'w') as file:
file.write('\n'.join(file_lines))
except:
messagebox.showerror("Error saving to file",
"Some problem happened while saving puzzle to the file.",
parent=parent)
# Save to file button widgget
评论列表
文章目录