Python Forum
[Tkinter] Issue with calling a Class/Method in GUI File
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Issue with calling a Class/Method in GUI File
#1
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.
Reply
#2
Try calling it with a name:

application = app()
Reply
#3
(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 !
Reply
#4
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Video [PyQt] Get a executable file (.exe) from a .py file add a promoted class in a QWidget MiguelonReyes 0 614 Oct-17-2023, 11:43 PM
Last Post: MiguelonReyes
Lightbulb [Tkinter] Tkinter Class Import Module Issue AaronCatolico1 6 2,970 Sep-06-2022, 03:37 PM
Last Post: AaronCatolico1
  [PyQt] I get a name Name Error: when calling a method inside a class radoo 2 2,325 Jun-11-2020, 05:02 PM
Last Post: radoo
  [Kivy] How do I reference a method in another class? Exsul1 3 4,219 Mar-02-2020, 07:32 PM
Last Post: Exsul1
  [Tkinter] Call a class method from another (Tk GUI) class? Marbelous 3 6,133 Jan-15-2020, 06:55 PM
Last Post: Marbelous
  Problem In calling a Function from another python file of project vinod2810 7 5,217 Oct-05-2019, 01:09 PM
Last Post: ichabod801
  Issue while importing variable from one file to other mamta_parida 14 6,226 Aug-29-2018, 11:40 AM
Last Post: mamta_parida
  [Tkinter] Class with text widget method AeranicusCascadia 3 7,738 Nov-14-2017, 11:33 PM
Last Post: AeranicusCascadia
  How to define a method in a class 1885 2 4,617 Oct-29-2017, 02:00 AM
Last Post: wavic
  [PyQt] How to put class method into new module? California 0 2,883 Jan-18-2017, 04:05 PM
Last Post: California

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020