Python Forum

Full Version: Issue with calling a Class/Method in GUI File
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello guys,

Currently I've a strange issue. I tried to google a lot but it seems that I'm either to dumb, or hopefully to blind to get the point of my issue..


I've a GUI in a file called gui.py
The radio button is set to 'off' as default, when I clock on 'on' I want to call a class in an other file, which logs in to a website and so on.

Current code:
File: gui.py
from tkinter import *
from tkinter import ttk
from tkinter import messagebox

from app import *

def login():
    print('Login')
    app()

# window object
app = Tk()
app.title('App')
app.geometry('450x400')

#setup TABS
tab_parent = ttk.Notebook(app)

tab_main= ttk.Frame(tab_parent)
tab_troops= ttk.Frame(tab_parent)
tab_building= ttk.Frame(tab_parent)
tab_settings= ttk.Frame(tab_parent)

tab_parent.add(tab_main, text='main')
tab_parent.add(tab_troops, text='troops')
tab_parent.add(tab_building,text='building')
tab_parent.add(tab_settings, text='settings')

# replace ->db
username="player1"
server="https://tx3.travian.de/"

# === WIDGETS Tab 1
nameLabel_tab_main = Label(tab_main, font=('bold',10), text='username:', pady=5)
nameLabel_tab_main.grid(row=0, column=0, sticky=W)
serverLabel_tab_main = Label(tab_main,font=('bold',10), text='server:')
serverLabel_tab_main.grid(row=1, column=0, sticky=W)

nameEntry_tab_main=Label(tab_main, text=username)
nameEntry_tab_main.grid(row=0, column=1,sticky=W)
serverEntry_tab_main=Label(tab_main, text=server)
serverEntry_tab_main.grid(row=1, column=1,sticky=W)

#placeholder frame for future feature ? log / current task next task whatever
PLACEHOLDERframe = Frame(tab_main, width=400,height=250).grid(row=2,column=0,columnspan=4)

# Switch ON/OFF
switch_variable = StringVar(value='off')
off_button = Radiobutton(tab_main, text="Off", variable=switch_variable, indicatoron=False, value="off", width=25).grid(row=8,column=0,columnspan=2)
on_button = Radiobutton(tab_main, text="On", variable=switch_variable, indicatoron=False, value="on", width=25,command=login).grid(row=8,column=2,columnspan=2)

# dont work as label for now ? -> Entry works
testEntry = Label(tab_main, text=switch_variable).grid(row=4,column=0)

# output to form
tab_parent.grid(row=0, column=0, columnspan=4, rowspan=10)

# mainloop
app.mainloop()
File app.py


class app(object):
    def __init__(self):
        
        self.session = requests.Session()
        self.config = {}
        self.loggedIn = False
          

        self.getJsonFileContent('config') 

        while 1:
            if self.checkLoginStatus():
                self.getHeroHealth()
                
            else:
                self.login()

            time.sleep(10)


.
.
.
.

actually i just tried to set a command "login" to the button.
on_button = Radiobutton(tab_main, text="On", variable=switch_variable, indicatoron=False, value="on", width=25,command=login).grid(row=8,column=2,columnspan=2)
The Method gets called, but as soon as the imported class should get called it interrupts...

Error: appears as soon as i hit "on" so the function/class gets called ...
Error:
Login Exception in Tkinter callback Traceback (most recent call last): File "C:\Python37\lib\tkinter\__init__.py", line 1705, in __call__ return self.func(*args) File "c:\workplace\Travian TaktikBot\TaktikBot\src\gui.py", line 9, in login app() TypeError: 'Tk' object is not callable
I dont really get it why It shouldnt be possible to call this class, or any method out of it.

I try to split the gui with the logic as good as possible. Therefore I need to be able to call other methods/classes.

What exactly do i need to do, to be able to call this class ? :)

Many thanks in advance.
Try calling it with a name:

application = app()
(Mar-08-2020, 07:08 AM)michael1789 Wrote: [ -> ]Try calling it with a name:

application = app()

Thanks for your reply.

unfortunately I tried that already.

Here are some things I've tried.

app = app() -> same error
app = app().login()   -> same error

The following is working ?
import utils    # this module only contains methods ! there is NO class

def login():
    print('Login')
    #application = app()
    test = utils.calcExpireDate('2000') 
    print(test)
In the latest test I simply tried to call a method from an other module, where is no class.

So I guess it has to do something with the class ? Because I can call a method from an other module ...


Anyone has some additionals ideas whats happening here ?
Is this any TK related issue, or am I messing something up with my classes.

Thanks in advance !
Short update from my side.

Since I didnt thought that there were any mistakes while calling the other class, I rebuilded simply everything, with some basics functions like the login , webscraper and so on.

Everythig seems to work now.
I didnt changed too much. Actually Nearly nothing.

Here is a snippet of the working code, for documentation if anyone has a similar issue.

gui.py
from tkinter import *
from tkinter import ttk

from app import ThisIsATest
from api import app

class Window(Tk):
    def __init__(self):
        super(Window, self).__init__()

        self.title("Tkinter OOP Window")
        self.geometry('500x400')

        self.button = ttk.Button(text = "Click", command=self.clickMe)
        self.button.grid(column=0, row=0)

    def clickMe(self):
        # call of the class
        api = app()
        
window = Window()
window.mainloop()
api.py
class app():
    def __init__(self):
        
        self.session = requests.Session()
        self.config = {}
        self.loggedIn = False
          
        self.testMethod()


    def testMethod(self):
        print('Run test Meethod')
        self.getJsonFileContent('config') 
        print(self.config['username'])
        

# METHODS ==================================================================
# ================= getJsonFileContent() =================
    def getJsonFileContent(self, param):
        # read in config file
        print(param)
        if(param == 'config'):
            try:
                with open('config.json', 'r') as configFile:
                    self.config=json.load(configFile)
                    configFile.close()
                
                logger.info(" READ config File ")
            except:
                logger.warning("Could not read in config file")

        # elif not need right now  cookies saved in self.cookies !
        elif (param == 'cookies'):
            try:
                pass #  r+   for read and write !

            except:
                logger.warning("Could not read in cookies file")
# ================= END OF getJsonFileContent() =================
Output:
Run test Meethod config player1
Well kinda strange, but as long as its working, its fine for me ^^

Anyways thanks for reading