How can you initialise an instance in a Kivy screen widget

2024/11/23 4:19:16

I am trying to access an instance variable named self.localId in my kivy screen and it keeps saying the saying the instance doesn't exist after i have initialised it. I know I have an error In my code but im having a hard time identifying it. is there a different way to initialising instances in a kivy screen? but here is my code. I would appreciate any help

mainfile.py

from kivy.app import App
import requests
import json
from kivy.uix.screenmanager import Screen, ScreenManager
from kivy.lang import Builder
from firebase import firebaseclass LoginWindow(Screen):passclass ProfileWindow(Screen):def __init__(self):self.localId = Nonedef sign_in_existing_user(self, email, password):signin_url = "https://www.googleapis.com/identitytoolkit/v3/relyingparty/verifyPassword?key=" + self.waksignin_payload = {"email": email, "password": password, "returnSecureToken": True}signin_request = requests.post(signin_url, data=signin_payload)sign_up_data = json.loads(signin_request.content.decode())app = App.get_running_app()print(signin_request.ok)print(signin_request.content.decode())if signin_request.ok == True:refresh_token = sign_up_data['refreshToken']self.localId = sign_up_data['localId']idToken = sign_up_data['idToken']# Save refreshToken to a filewith open(app.refresh_token_file, "w") as f:f.write(refresh_token)print(sign_up_data['localId'])app.root.current = "page"elif signin_request.ok == False:error_data = json.loads(signin_request.content.decode())error_message = error_data["error"]['message']app.root.ids.login.ids.login_message.text = error_message.replace("_", " ")def print_localId(self):print(self.localId.text)def __init__(self, **kwargs):super(ProfileWindow, self).__init__(**kwargs)window = ProfileWindow()class MyApp(App):refresh_token_file = "refresh_token.txt"def build(self):self.page = ProfileWindow()self.refresh_token_file = self.user_data_dir + self.refresh_token_filereturn smclass WindowManager(ScreenManager):passsm = Builder.load_file("kivy.kv")#sm = WindowManager() if __name__ == '__main__':MyApp().run()

kivy.kv

WindowManager:id: window managerLoginWindow:id: loginname: "login"ProfileWindow:id: pagename: "page"<LoginWindow>canvas.before:Color:rgba: 1, 1, 1, 1Rectangle:pos: self.possize: self.sizeTextInput:id: emailhint_text: "Email"multiline: Falsepos_hint: {"center_x": 0.2 , "center_y":0.9}size_hint: 0.4, 0.10TextInput:id: passwordhint_text: "Password"multiline: Falsepos_hint: {"center_x": 0.2, "center_y": 0.8}size_hint: 0.4, 0.10password: TrueButton:pos_hint:{"x":0.3,"y":0.05}size_hint: 0.4, 0.1text: "Login"font_size: (root.width**2 + root.height**2)  / 14**4background_color: (0.082, 0.549, 0.984, 1.0)background_normal: ''on_release:app.page.sign_in_existing_user(email.text, password.text)<ProfileWindow>:canvas.before:Color:rgba: 1, 1, 1, 1Rectangle:pos: self.possize: self.sizeButton:pos_hint:{"x":0.3,"y":0.05}size_hint: 0.4, 0.1text: "Print localId"font_size: (root.width**2 + root.height**2)  / 14**4background_color: (0.082, 0.549, 0.984, 1.0)background_normal: ''on_release:root.print_localId()

Traceback

[INFO   ] [Base        ] Leaving application in progress...
Traceback (most recent call last):File "/Users/temitayoadefemi/PycharmProjects/test6/mainfile.py", line 109, in <module>MyApp().run()File "/Users/temitayoadefemi/PycharmProjects/test6/venv/lib/python3.7/site-packages/kivy/app.py", line 855, in runrunTouchApp()File "/Users/temitayoadefemi/PycharmProjects/test6/venv/lib/python3.7/site-packages/kivy/base.py", line 504, in runTouchAppEventLoop.window.mainloop()File "/Users/temitayoadefemi/PycharmProjects/test6/venv/lib/python3.7/site-packages/kivy/core/window/window_sdl2.py", line 747, in mainloopself._mainloop()File "/Users/temitayoadefemi/PycharmProjects/test6/venv/lib/python3.7/site-packages/kivy/core/window/window_sdl2.py", line 479, in _mainloopEventLoop.idle()File "/Users/temitayoadefemi/PycharmProjects/test6/venv/lib/python3.7/site-packages/kivy/base.py", line 342, in idleself.dispatch_input()File "/Users/temitayoadefemi/PycharmProjects/test6/venv/lib/python3.7/site-packages/kivy/base.py", line 327, in dispatch_inputpost_dispatch_input(*pop(0))File "/Users/temitayoadefemi/PycharmProjects/test6/venv/lib/python3.7/site-packages/kivy/base.py", line 293, in post_dispatch_inputwid.dispatch('on_touch_up', me)File "kivy/_event.pyx", line 707, in kivy._event.EventDispatcher.dispatchFile "/Users/temitayoadefemi/PycharmProjects/test6/venv/lib/python3.7/site-packages/kivy/uix/behaviors/button.py", line 179, in on_touch_upself.dispatch('on_release')File "kivy/_event.pyx", line 703, in kivy._event.EventDispatcher.dispatchFile "kivy/_event.pyx", line 1214, in kivy._event.EventObservers.dispatchFile "kivy/_event.pyx", line 1098, in kivy._event.EventObservers._dispatchFile "/Users/temitayoadefemi/PycharmProjects/test6/venv/lib/python3.7/site-packages/kivy/lang/builder.py", line 64, in custom_callbackexec(__kvlang__.co_value, idmap)File "/Users/temitayoadefemi/PycharmProjects/test6/kivy.kv", line 86, in <module>root.print_localId()File "/Users/temitayoadefemi/PycharmProjects/test6/mainfile.py", line 73, in print_localIdprint(self.localId.text)
AttributeError: 'ProfileWindow' object has no attribute 'localId'
Answer

You have two __init__() methods in ProfileWindow. The second redefines, overwriting the first, and does not create the localId attribute. Your one and only __init__() method in ProfileWindow should be:

   def __init__(self, **kwargs):super(ProfileWindow, self).__init__(**kwargs)self.localId = None

The next problem is that you are creating 3 instances of ProfileWindow. You only need one. So remove the line:

window = ProfileWindow()

and from your build() method in the App, remove:

self.page = ProfileWindow()

The ProfileWindow is created by the line in your code:

sm = Builder.load_file("kivy.kv")

any other use of ProfileWindow() creates a new instance of ProfileWindow that is not part of your GUI.

Next, you need to access the correct instance of ProfileWindow when you press the Login Button. To do that, make use of the ids in your kv file as:

    on_release:app.root.ids.page.sign_in_existing_user(email.text, password.text)

And, what I think is the final error, your print_localId() method tries to print the text attribute of localId, but it does not have such an attribute. Just change that method to:

   def print_localId(self):print(self.localId)
https://en.xdnf.cn/q/120660.html

Related Q&A

is a mathematical operator classed as an interger in python

in python is a mathematical operator classed as an interger. for example why isnt this code workingimport randomscore = 0 randomnumberforq = (random.randint(1,10)) randomoperator = (random.randint(0,2)…

Fix a function returning duplicates over time?

I have a function here that returns a 4 digit string. The problem is that when I run the function like 500 times or more, it starts to return duplicates. How to avoid that?My Function:import random de…

Pandas method corr() use not all features

I have dataframe with shape (335539, 26). So I have 26 features. But when i use data.corr() I get a 12 x 12 matrix.What can be wrong? `

int to datetime in Python [duplicate]

This question already has answers here:Convert string "Jun 1 2005 1:33PM" into datetime(26 answers)Parsing datetime in Python..?(2 answers)Closed 5 years ago.Im receiving data from the port.…

How to extract the historical tweets from twitter API? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.Want to improve this question? Update the question so it focuses on one problem only by editing this post.Closed 5…

ValueError: invalid literal for int() with base 16: [closed]

Closed. This question needs debugging details. It is not currently accepting answers.Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to repro…

Modify list in Python [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable…

How to delete files inside hidden folder with python? [duplicate]

This question already has answers here:How can I delete a file or folder in Python?(18 answers)Closed 5 years ago.I want do delete a file, for ex. myfile.txt that is stored under a hidden folder. Is i…

Matching keywords in a dictionary to a list in Python

The following dictionary gives the word and its value:keywords = {alone: 1, amazed: 10, amazing: 10, bad: 1, best: 10, better: 7, excellent: 10, excited: 10, excite: 10}Following the dictionary are two…

How to make case insensitive? [closed]

Its difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying thi…