Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

ฟังก์ชัน asksaveasfile() ใน Python Tkinter

Tkinter เป็นโมดูล Python สำหรับการเขียนโปรแกรม GUI เราสร้าง Canvas และวางคอมโพเนนต์ UI ต่างๆ พร้อมคุณสมบัติและพฤติกรรม บทความนี้จะแสดงวิธีใช้ฟังก์ชัน asksaveasfile เพื่อบันทึกไฟล์ที่สร้างโดยโปรแกรม Python ลงในดิสก์ท้องถิ่น

เราสร้าง Canvas ก่อน แล้ววางปุ่มโดยใช้ฟังก์ชัน ttk.Button จากนั้นประกาศฟังก์ชันอีกตัวที่จะใช้ asksaveasfile กำหนดประเภทไฟล์และบันทึกไฟล์ไปยังตำแหน่งในดิสก์ท้องถิ่น

ตัวอย่าง

from tkinter import *
from tkinter import ttk
from tkinter.filedialog import asksaveasfile

base = Tk()
base.geometry('300x250')

def SaveFile():
    data = [('All types (*.*)', '*.*')]
    file = asksaveasfile(filetypes=data, defaultextension=data)

save_btn = ttk.Button(base, text='Click to save file', command=lambda: SaveFile())
save_btn.pack(side=TOP, pady=20, padx=50)
mainloop()

ผลลัพธ์

การรันโค้ดข้างต้นจะแสดงหน้าต่าง GUI ดังนี้

ฟังก์ชัน asksaveasfile() ใน Python Tkinter

เมื่อคลิกปุ่ม "Click to save file" จะแสดงหน้าต่างบันทึกไฟล์ดังนี้

ฟังก์ชัน asksaveasfile() ใน Python Tkinter