How to split Python Tkinter code in multiple files

This is my first post here!

First here is the github link (I'm a noob on github too) of my project .

Edited:

So here is an example of what I want to do, I have a large Tkinter class with frames, labels, menus, buttons and all and some of the functions in it.

I want to describe the UI in my MakeUI () and move my funcs to another file, but I still need to be able to access the widgets.

<Main.py>

# -*- coding: utf-8 -*-

from tkinter import *
from Interface import *


Fenetre = Tk()
UI = MakeUI(Fenetre)

UI.mainloop()

UI.destroy()

      

<Interface.py>

# -*- coding: utf-8 -*-

from tkinter import *
from tkinter.filedialog import *


class MakeUI(Frame):

    def __init__(self, Fenetre, **kwargs):

        # Héritage
        Frame.__init__(self, Fenetre, width=1500, height=700, **kwargs)

        self.pack(fill=BOTH)

        self.FrameInfos = LabelFrame(self, text="Choix des paramètres", padx=2, pady=2)
        self.FrameInfos.pack(fill="both", expand="yes", padx=5, pady=5)

        self.MsgInfosCarte = Label(self.FrameInfos, text="Example", width=45)
        self.MsgInfosCarte.pack(padx=2, pady=2)

    def AfficherCarte(self):
        self.MsgInfosCarte["text"] = "OK"

      

And now in this example, I need to move the AfficherCarte function to another file like MapFuncs.py or else. And I want the MakeUI to be able to call other funcs files and other funcs files to change the interface.

I cannot get it right.

Thank you for your help.

+3


source to share


1 answer


To move a function that modifies your GUI widget in a separate file, you can simply pass an instance of the widget (or the object that stores that instance) as an input argument to your function:

<MapFuncs.py>

def AfficherCarte(UI):
    UI.MsgInfosCarte["text"] = "OK"

      



<Interface.py>

import tkinter as tk
from MapFuncs import AfficherCarte

class MakeUI(tk.Frame):

    def __init__(self, Fenetre, **kwargs):

        # Héritage
        tk.Frame.__init__(self, Fenetre, width=1500, height=700, **kwargs)
        self.pack()

        self.FrameInfos = tk.LabelFrame(self, text="Choix des paramètres", padx=2, pady=2)
        self.FrameInfos.pack(fill="both", expand="yes", padx=5, pady=5)

        self.MsgInfosCarte = tk.Label(self.FrameInfos, text="Example", width=45)
        self.MsgInfosCarte.pack(padx=2, pady=2)

        # Call function from external file to modify the GUI
        AfficherCarte(self)

      

If you are doing this because your code is getting too large, another way would be to split your GUI into separate classes for each main part of the interface (see fooobar.com/questions/90307 / ... ).

0


source







All Articles