Home > Enterprise >  Calling a function exists in class "a", from "b" class, tkinter caused opening t
Calling a function exists in class "a", from "b" class, tkinter caused opening t

Time:05-29

Problem description:

Have two classes in different .py files. Class 1: App(tk.Tk) located in new.py Class 2: CustomNotebook(ttk.Notebook) located in formed.py When a class 1 function is called from class 2 the app starts second time.

What I wanted to achieve: To call "close_action" function located in class 1 without reopening the app second time.

Additional description: The function is called when it was called from class 2.

You may see the code down below. The class 1 has about 1k lines, so I trimmed the functions that do not interact with our subject function.

Class 1 code:

import itertools
import io
import os
import random
import sqlite3
import string
import formed
from sqlite3 import Error
from tkinter.ttk import Entry, Label
import tkinter as tk
from tkinter import *
from tkinter.scrolledtext import ScrolledText
import logging
import time
from time import strftime
from datetime import date
from tkinter import ttk, filedialog, messagebox
from PIL import Image, ImageTk

logging.basicConfig(filename='db/log_file.log', encoding='utf-8', level=logging.DEBUG)


class App(tk.Tk):

    def __init__(self):
        super().__init__()
        self.frame_person_list_bool = False
        self.frame_add_person_bool = False
        self.frame_person_theraphy_bool = False
        self.my_menu = None
        self.first_column = None
        self.second_column = None
        self.width = None
        self.height = None
        self.error_tuple = (AssertionError, AttributeError, EOFError, FloatingPointError, GeneratorExit, ImportError,
                            IndexError, KeyError, KeyboardInterrupt, MemoryError, NameError, NotImplementedError,
                            OSError, OverflowError, ReferenceError, RuntimeError, StopIteration, SyntaxError,
                            IndentationError, TabError, SystemError, SystemExit, TypeError, UnboundLocalError,
                            UnicodeError, UnicodeEncodeError, UnicodeDecodeError, UnicodeTranslateError, ValueError,
                            ZeroDivisionError, Error, TclError)
        self.message_label = Label(self, text="")
        self.time_label = Label(self)
        self.date_label = Label(self)
        self.day_label = Label(self)
        self.fob = None
        self.main_screen_values(main_title="Terapi Takip Programı", icon_path='images/novaic.ico')


    def button_checker(self):
        """
            DISABLED ENABLED butonların kontrol edildiği yer
        """
        if self.frame_person_list_bool is True:
            self.first_column.entryconfig("Kişi Listesi", state=DISABLED)
        if self.frame_person_list_bool is False:
            self.first_column.entryconfig("Kişi Listesi", state=NORMAL)
        if self.frame_add_person_bool is True:
            self.first_column.entryconfig("Kişi Ekle", state=DISABLED)
        if self.frame_add_person_bool is False:
            self.first_column.entryconfig("Kişi Ekle", state=NORMAL)

    def close_action(self, value):

        print("worked")
        if value == "Kişi Ekle":
            self.frame_add_person_bool = False
            self.button_checker()
        if value == "Kişi Listesi":
            self.frame_person_list_bool = False
            self.button_checker()
        if value == "Tedavi Sayfası":
            self.frame_person_theraphy_bool = False
            self.button_checker()

if __name__ == "__main__":
    app = App()
    app.mainloop()

Class 2 code: The code that calls class 1 new.App.close_action(new.App(), value=self.value).

import tkinter as tk
from tkinter import ttk
import new

class CustomNotebook(ttk.Notebook):
    """A ttk Notebook with close buttons on each tab"""

    __initialized = False

    def __init__(self, *args, **kwargs):
        if not self.__initialized:
            self.__initialize_custom_style()
            self.__inititialized = True

        kwargs["style"] = "CustomNotebook"
        ttk.Notebook.__init__(self, *args, **kwargs)

        self._active = None
        self.value = None
        self.bind("<ButtonPress-1>", self.on_close_press, True)
        self.bind("<ButtonRelease-1>", self.on_close_release)

    def on_close_press(self, event):
        """Called when the button is pressed over the close button"""

        element = self.identify(event.x, event.y)

        if "close" in element:
            index = self.index("@%d,%d" % (event.x, event.y))
            self.state(['pressed'])
            self._active = index
            self.value = CustomNotebook.tab(self, tab_id=index, option="text")
            new.App.close_action(new.App(), value=self.value)
            return "break"

    def on_close_release(self, event):
        """Called when the button is released"""

        if not self.instate(['pressed']):
            return

        element = self.identify(event.x, event.y)
        if "close" not in element:
            # user moved the mouse off of the close button
            return

        index = self.index("@%d,%d" % (event.x, event.y))

        if self._active == index:
            self.forget(index)
            self.event_generate("<<NotebookTabClosed>>")

        self.state(["!pressed"])
        self._active = None


    def __initialize_custom_style(self):
        style = ttk.Style()
        self.images = (
            tk.PhotoImage("img_close", data='''
                R0lGODlhCAAIAMIBAAAAADs7O4 Pj9nZ2Ts7Ozs7Ozs7Ozs7OyH EUNyZWF0ZWQg
                d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
                5kEJADs=
                '''),
            tk.PhotoImage("img_closeactive", data='''
                R0lGODlhCAAIAMIEAAAAAP/SAP/bNNnZ2cbGxsbGxsbGxsbGxiH5BAEKAAQALAAA
                AAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU5kEJADs=
                '''),
            tk.PhotoImage("img_closepressed", data='''
                R0lGODlhCAAIAMIEAAAAAOUqKv9mZtnZ2Ts7Ozs7Ozs7Ozs7OyH EUNyZWF0ZWQg
                d2l0aCBHSU1QACH5BAEKAAQALAAAAAAIAAgAAAMVGDBEA0qNJyGw7AmxmuaZhWEU
                5kEJADs=
            ''')
        )

        style.element_create("close", "image", "img_close",
                             ("active", "pressed", "!disabled", "img_closepressed"),
                             ("active", "!disabled", "img_closeactive"), border=8, sticky='')
        style.layout("CustomNotebook", [("CustomNotebook.client", {"sticky": "nswe"})])
        style.layout("CustomNotebook.Tab", [
            ("CustomNotebook.tab", {
                "sticky": "nswe",
                "children": [
                    ("CustomNotebook.padding", {
                        "side": "top",
                        "sticky": "nswe",
                        "children": [
                            ("CustomNotebook.focus", {
                                "side": "top",
                                "sticky": "nswe",
                                "children": [
                                    ("CustomNotebook.label", {"side": "left", "sticky": ''}),
                                    ("CustomNotebook.close", {"side": "left", "sticky": ''}),
                                ]
                            })
                        ]
                    })
                ]
            })
        ])

CodePudding user response:

new.App.close_action(new.App(), value=self.value)

In my opinion, new.App() calls the class. You should try this.

new.App.close_action(new.App, value=self.value)

CodePudding user response:

You need to call close_action on the already created instance of App. What is happening is that when you do new.App() you are explicitly creating a new instance of App.

The best way to achieve that is for you to pass the instance of App to CustomNotebook, or get it from an import.

So, instead of new.App.close_action(new.App(), value=self.value) it needs to be something like new.app.close_action(value=self.value, where app is the instance. This assumes that new is the module that does app = App()

  • Related