البرمجة

حفظ بيانات الإدخال في Python

To address the issue with your file_save_as function in Python using Tkinter, you need to make a few adjustments. The main issue in your code is that you are opening the file with the string 'fout' instead of using the fout variable, which holds the file object returned by asksaveasfile. Here’s the corrected version of your function:

python
from tkinter.filedialog import asksaveasfile from tkinter import Tk, Entry class YourClassName: def __init__(self): self.entries = [] # Assume this is populated with Entry widgets def file_save_as(self): fout = asksaveasfile(mode='w', defaultextension='.txt') if fout is None: # User canceled the save dialog return with fout: for entry in self.entries: text = entry.get() # Get the text from each Entry widget fout.write("%s\n" % text) # Example usage root = Tk() app = YourClassName() app.file_save_as() root.mainloop()

This code assumes that self.entries is a list containing all the Entry widgets you want to save the data from. It iterates over each Entry widget, gets the text using entry.get(), and writes it to the file using fout.write(). The asksaveasfile function is used to prompt the user to select a file to save the data to.

المزيد من المعلومات

لحل مشكلتك بإنشاء وظيفة “حفظ ك” في Python باستخدام Tkinter ، يمكنك تحسين الكود لضمان أنه يتم حفظ بيانات الإدخال النصي من جميع عناصر الإدخال بشكل صحيح. إليك كيفية تحسين الكود:

  1. تأكد من أن self.entries هو قائمة تحتوي على جميع عناصر الإدخال التي تريد حفظ البيانات منها.
  2. استخدم fout.name بدلاً من 'fout' عند فتح الملف لحفظ البيانات في الملف الذي تم اختياره بواسطة المستخدم.

قد يكون الكود كما يلي:

python
from tkinter.filedialog import asksaveasfile from tkinter import Tk, Entry class YourClassName: def __init__(self): self.entries = [] # يجب ملء هذه القائمة بعناصر Entry def file_save_as(self): fout = asksaveasfile(mode='w', defaultextension='.txt') if fout is None: # إذا ألغى المستخدم الحفظ return with fout: for entry in self.entries: text = entry.get() # الحصول على النص من كل عنصر إدخال fout.write("%s\n" % text) # مثال على الاستخدام root = Tk() app = YourClassName() app.file_save_as() root.mainloop()

هذا الكود يفترض أن self.entries هو قائمة تحتوي على جميع عناصر الإدخال التي تريد حفظ البيانات منها. يتم الحصول على النص من كل عنصر إدخال باستخدام entry.get() ويتم حفظه في الملف المختار باستخدام fout.write(). asksaveasfile يستخدم لطلب من المستخدم تحديد ملف لحفظ البيانات فيه.

زر الذهاب إلى الأعلى