اذهب إلى المحتوى
  • 0

تصحيح مشكلة الكود

Ahmed Ahmed64

السؤال

السلام عليكم

import tkinter as tk
from tkinter import filedialog, messagebox, ttk
import pandas as pd

class App(tk.Tk):
    def __init__(self):
        super().__init__()
        self.title("App-v1")
        self.columnconfigure(0, weight = 1)
        self.rowconfigure(1, weight = 1)
        Menu(self)
        Load_excel_data()
    
    def File_dialog(self):
        """This Function will open the file explorer and assign the chosen file path to label_file"""
        filename = filedialog.askopenfilename(initialdir="/",
                                              title="Select A File",
                                              filetype=(("xlsx files", "*.xlsx"),("All Files", "*.*")))
        label_file["text"] = filename
        return None


    def Load_excel_data():
        """If the file selected is valid this will load the file into the Treeview"""
        file_path = label_file["text"]
        try:
            excel_filename = r"{}".format(file_path)
            if excel_filename[-4:] == ".csv":
                df = pd.read_csv(excel_filename)
            else:
                df = pd.read_excel(excel_filename)

        except ValueError:
            tk.messagebox.showerror("Information", "The file you have chosen is invalid")
            return None
        except FileNotFoundError:
            tk.messagebox.showerror("Information", f"No such file as {file_path}")
            return None

class Menu(ttk.Frame):
    def __init__(self, parent):
        super().__init__(parent)
        
        self.grid(row=0, column=0, padx=(10, 10), pady=(10, 10), sticky="e")
        self.columnconfigure(0, weight = 1)
        self.rowconfigure(1, weight = 1)
        self.create_widgets()

    def create_widgets(self):
        self.menu_button1 = ttk.Button(self, text = 'Button 1',command=File_dialog)
        self.menu_button1.grid(row = 0, column = 0, sticky = 'e')

app = App()
app.mainloop()

 

رابط هذا التعليق
شارك على الشبكات الإجتماعية

Recommended Posts

  • 0

لديك بعض المشكلات في الربط بين الكلاسات في الكود الخاص بك، يجب عليك تصحيح الطريقة التي تقوم بها بتمرير الـ method إلى الأزرار داخل Frame2،  يجب تمرير instance من الكلاس App إلى Frame2  واستخدام هذا الـ instance لاستدعاء الـ LoadFile و LoadFile1.

إليك الكود المصحح:

import customtkinter
from tkinter import filedialog
from pathlib import Path
import pandas as pd

class App(customtkinter.CTk):
    def __init__(self):
        super().__init__()
        self.FilePath = None
        self.sh = None
        self.title("App-v1")
        self.grid_columnconfigure(0, weight=1)
        self.grid_rowconfigure(1, weight=1)

        customtkinter.set_appearance_mode("dark")
        customtkinter.set_default_color_theme("green")

        Frame_A = Frame1(self)
        Frame_A.grid(row=0, column=0, padx=(10, 10), pady=(10, 10), sticky="ew", columnspan=2)
        Frame_A.grid_columnconfigure(0, weight=1)
        Frame_A.configure(border_width=1, border_color="#0087f2")

        Frame_B = Frame2(self)
        Frame_B.grid(row=1, column=0, padx=(10, 10), pady=(10, 10), sticky="news")
        Frame_B.grid_columnconfigure(0, weight=1)
        Frame_B.configure(border_width=1, border_color="#0087f2")

    def LoadFile(self):
        self.FilePath = filedialog.askopenfilename(initialdir="C:\\Users\\Cakow\\PycharmProjects\\Main",
                                                    title="Open file okay?", filetypes=(("text files", "*.xlsx"),
                                                                                          ("all files", "*.*")))
        return self.FilePath

    def LoadFile1(self):
        df = pd.ExcelFile(self.FilePath)
        self.sh = df.sheet_names
        print(self.sh)


class Frame1(customtkinter.CTkFrame):
    def __init__(self, master):
        super().__init__(master)

        self.label1 = customtkinter.CTkLabel(self, text="Welcome", fg_color="transparent",
                                             font=customtkinter.CTkFont(family="Calibri", size=18, weight="bold"),
                                             justify="center")
        self.label1.grid(row=0, column=0, padx=(10, 10), pady=(10, 10), sticky="n")


class Frame2(customtkinter.CTkFrame):
    def __init__(self, master):
        super().__init__(master)

        # تمرير الـ instance من الـ App لـ Frame2
        self.button1 = customtkinter.CTkButton(self, text="Open File", font=customtkinter.CTkFont(family="Calibri", size=12, weight="bold"),
                                               command=master.LoadFile)  # استخدام الـ instance لاستدعاء الـ method
        self.button1.grid(row=0, column=0, padx=(10, 10), pady=(10, 10), sticky="e")

        self.button2 = customtkinter.CTkButton(self, text="Open File", font=customtkinter.CTkFont(family="Calibri", size=12, weight="bold"),
                                               command=master.LoadFile1)  # استخدام الـ instance لاستدعاء الـ method
        self.button2.grid(row=0, column=1, padx=(10, 10), pady=(10, 10), sticky="e")

app = App()
app.mainloop()

قمت بتعديل الأزرار داخل Frame2 لتمرير الـ instance الخاصة بـ App واستخدمتها لاستدعاء الـ method.

رابط هذا التعليق
شارك على الشبكات الإجتماعية

انضم إلى النقاش

يمكنك أن تنشر الآن وتسجل لاحقًا. إذا كان لديك حساب، فسجل الدخول الآن لتنشر باسم حسابك.

زائر
أجب على هذا السؤال...

×   لقد أضفت محتوى بخط أو تنسيق مختلف.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   جرى استعادة المحتوى السابق..   امسح المحرر

×   You cannot paste images directly. Upload or insert images from URL.

  • إعلانات

  • تابعنا على



×
×
  • أضف...