Aidan Williams
Aidan Williams

Reputation: 31

Name is not defined when using variables and functions in Kivy

I'm creating a program that interacts with a server, this program is for employees to use on a mobile device, so I'm using Kivy, and I'm doing the GUI first. I followed the instructions on the documentation to the best of my understanding, but cannot seem to solve this problem. My code refers to variables and functions, but, whenever it runs it crashes and gives me and error code stating that the name of a variable or function (whichever is called first) is not defined

Here's my code:

import sqlalchemy
import os
import kivy
import datetime
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy import app
from kivy.uix import button
from kivy.uix.textinput import TextInput
from kivy.uix.label import Label
from kivy.lang import Builder

admincode = "..."
# SQL Functions
# Incomplete as of now
# shift will be pulled from database
shift = False

def UserLogin(id = 'unfilled', password = 'unfilled'):
    global user
    global localhost_enabled
    if id == "localtest" and password == admincode:
        user = id
        localhost_enabled = True
        return True
    elif id == "servertest" and password == admincode:
        user = id
        localhost_enabled = False
        return True
def UserLogout():
    user = ''

def ShiftIn():
    global shift
    shift = True
def ShiftOut():
    global shift
    shift = False
def submitform(StartCash=0, EndCash=0):
    NetCash = EndCash - StartCash
    print("NetCash = {0}".format(NetCash))
def ShiftGetter():
    if shift == True:
        return "Shift Out"
    else:
        return "Shift In"
# Kivy Building

Builder.load_string("""
<LoginScreen>:
    BoxLayout:
        Label:
            text: 'ID:'
        TextInput:
            id: LoginInputUser
            text: ''
            multiline: False
        Label:
            text: "Password:"
        TextInput:
            id: LoginInputPassword
            text: ''
            password: True
            multiline: False
        Button:
            text: 'login'
            on_press:
                if UserLogin(LoginInputUser.text, LoginInputPassword.text): LoginValidationText.text = ''
                if UserLogin(LoginInputUser.text, LoginInputPassword.text): root.manager.current = 'Home'
                else: LoginValidationText.text = 'Invalid Username or Password'
        Label:
            text: ''
            id: 'LoginValidationText'


<HomeScreen>:
    BoxLayout:
        Button:
            text: 'Logout'
            on_press:
                UserLogout()
                root.manager.current = 'Login'
        Button:
            text: 'Open Submission Form'
            on_press: root.manager.current = 'Form'
        Button:
            text: 'Shift Out' if shift == True else 'Shift In'
            on_press:
                if shift: ShiftOut()
                else: ShiftIn()


<FormScreen>:
    BoxLayout:
        Button:
            text: 'Back to menu'
            on_press: root.manager.current = 'Home'
        Label:
            text: 'Start Money:'
        TextInput:
            id: StartCash
            text: ''
            multiline: False
        Label:
            text: 'End Money:'
        TextInput:
            id: EndCash
            text: ''
            multiline: False
        Button:
            text: 'Submit'
            on_press: submitform(StartCash = int(StartCash.text), EndCash = int(EndCash.text))

""")
class LoginScreen(Screen):
    pass

class HomeScreen(Screen):
    pass

class FormScreen(Screen):
    pass

sm = ScreenManager()
sm.add_widget(LoginScreen(name='Login'))
sm.add_widget(HomeScreen(name='Home'))
sm.add_widget(FormScreen(name='Form'))
class RealApp(App):
    def build(self):
        return sm

RealApp().run()

And the error message:

[INFO   ] [Logger      ] Record log in C:\Users\sherl\.kivy\logs\kivy_17-08-20_28.txt
[INFO   ] [Kivy        ] v1.10.0
[INFO   ] [Python      ] v3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)]
[INFO   ] [Factory     ] 194 symbols loaded
[INFO   ] [Image       ] Providers: img_tex, img_dds, img_sdl2, img_gif (img_pil, img_ffpyplayer ignored)
[INFO   ] [Text        ] Provider: sdl2
[INFO   ] [OSC         ] using <thread> for socket
[INFO   ] [Window      ] Provider: sdl2
[INFO   ] [GL          ] Using the "OpenGL" graphics system
[INFO   ] [GL          ] GLEW initialization succeeded
[INFO   ] [GL          ] Backend used <glew>
[INFO   ] [GL          ] OpenGL version <b'4.4.0 - Build 20.19.15.4531'>
[INFO   ] [GL          ] OpenGL vendor <b'Intel'>
[INFO   ] [GL          ] OpenGL renderer <b'Intel(R) HD Graphics 5500'>
[INFO   ] [GL          ] OpenGL parsed version: 4, 4
[INFO   ] [GL          ] Shading version <b'4.40 - Build 20.19.15.4531'>
[INFO   ] [GL          ] Texture max size <16384>
[INFO   ] [GL          ] Texture max units <32>
[INFO   ] [Shader      ] fragment shader: <b"WARNING: 0:7: '' :  #version directive missing">
[INFO   ] [Shader      ] vertex shader: <b"WARNING: 0:7: '' :  #version directive missing">
[INFO   ] [Window      ] auto add sdl2 input provider
[INFO   ] [Window      ] virtual keyboard not allowed, single mode, not docked
 Traceback (most recent call last):
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 249, in create_handler
     return eval(value, idmap), bound_list
   File "<string>", line 39, in <module>
 NameError: name 'shift' is not defined

 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 597, in _apply_rule
     rctx['ids'])
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 254, in create_handler
     cause=tb)
 kivy.lang.builder.BuilderException: Parser: File "<inline>", line 39:
 ...
      37:            on_press: root.manager.current = 'Form'
      38:        Button:
 >>   39:            text: 'Shift Out' if shift == True else 'Shift In'
      40:            on_press:
      41:                if shift: ShiftOut()
 ...
 NameError: name 'shift' is not defined
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 249, in create_handler
     return eval(value, idmap), bound_list
   File "<string>", line 39, in <module>


 During handling of the above exception, another exception occurred:

 Traceback (most recent call last):
   File "C:\Users\sherl\PycharmProjects\PokerRoomSQL\User\UserDepreciated.py", line 126, in <module>
     sm.add_widget(HomeScreen(name='Home'))
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\relativelayout.py", line 265, in __init__
     super(RelativeLayout, self).__init__(**kw)
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\floatlayout.py", line 65, in __init__
     super(FloatLayout, self).__init__(**kwargs)
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\layout.py", line 76, in __init__
     super(Layout, self).__init__(**kwargs)
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\uix\widget.py", line 345, in __init__
     Builder.apply(self, ignored_consts=self._kwargs_applied_init)
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 451, in apply
     self._apply_rule(widget, rule, rule, ignored_consts=ignored_consts)
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 612, in _apply_rule
     e), cause=tb)
 kivy.lang.builder.BuilderException: Parser: File "<inline>", line 39:
 ...
      37:            on_press: root.manager.current = 'Form'
      38:        Button:
 >>   39:            text: 'Shift Out' if shift == True else 'Shift In'
      40:            on_press:
      41:                if shift: ShiftOut()
 ...
 BuilderException: Parser: File "<inline>", line 39:
 ...
      37:            on_press: root.manager.current = 'Form'
      38:        Button:
 >>   39:            text: 'Shift Out' if shift == True else 'Shift In'
      40:            on_press:
      41:                if shift: ShiftOut()
 ...
 NameError: name 'shift' is not defined
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 249, in create_handler
     return eval(value, idmap), bound_list
   File "<string>", line 39, in <module>

   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 597, in _apply_rule
     rctx['ids'])
   File "C:\Users\sherl\AppData\Local\Programs\Python\Python36-32\lib\site-packages\kivy\lang\builder.py", line 254, in create_handler
     cause=tb)

Upvotes: 3

Views: 5239

Answers (2)

4nakter
4nakter

Reputation: 157

I have same problem with similar code. My program its simple, coz i want just try it on simple-program and use that on other.

from kivymd.app import MDApp
from kivy.lang.builder import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.properties import ObjectProperty

class FirstWindow(Screen):
    pass

class ProfileWindow(Screen):
    pass

class WindowManager(ScreenManager):
    pass

sm = ScreenManager()
sm.add_widget(FirstWindow(name='first'))
sm.add_widget(ProfileWindow(name='secound'))

class AwesomeApp(MDApp):
    info_move = ObjectProperty(None)
    def build(self):
        info_move = ObjectProperty(None)
        return Builder.load_file('new_window.kv')

AwesomeApp().run()

And the new_window.kv

#:import ObjectProperty kivy.properties.ObjectProperty

ScreenManager:

    FirstWindow:
    ProfileWindow:

<FirstWindow>:
    name: 'first'
    MDRaisedButton:
        text: "Zmien okno"
        on_press: root.manager.current = 'profile'
    MDLabel:
        text: 'Pierwsze okno'

<ProfileWindow>:

    name: 'profile'
    MDRaisedButton:
        text: "Zmien okno"
        on_press: root.manager.current = 'first'
    MDTextField:
        id: info_move
        text: 'Drugie okno'
        pos_hint: {"center_x": .5, "center_y": .8}

No matter where i put info_move = ObjectProperty(None), when i put on .kv info_move: info_move i recive an error "Name is not defined" I need to type a string on "secound", click button, and move that text to label on "first" window. I check few options from internet, but nothing works for me.

Upvotes: 0

ikolim
ikolim

Reputation: 16011

You have the following errors:

  1. Change "from kivy import app" to "from kivy.app import App"
  2. Add "from kivy.properties import BooleanProperty"
  3. Replace "shift = False" to "shift = BooleanProperty(False)"
  4. Remove all references to "global shift"

I have separated the program into Python program and kv file as shown below.

Modifed main.py

import sqlalchemy
import os
import datetime

from kivy.app import App
from kivy.properties import BooleanProperty
from kivy.uix.screenmanager import ScreenManager, Screen

admincode = "..."
# SQL Functions
# Incomplete as of now
# shift will be pulled from database
shift = BooleanProperty(False)


def UserLogin(id='unfilled', password='unfilled'):
    global user
    global localhost_enabled
    if id == "localtest" and password == admincode:
        user = id
        localhost_enabled = True
        return True
    elif id == "servertest" and password == admincode:
        user = id
        localhost_enabled = False
        return True


def UserLogout():
    user = ''


def ShiftIn():
    shift = True


def ShiftOut():
    shift = False


def submitform(StartCash=0, EndCash=0):
    NetCash = EndCash - StartCash
    print("NetCash = {0}".format(NetCash))


def ShiftGetter():
    if shift:
        return "Shift Out"
    else:
        return "Shift In"


class LoginScreen(Screen):
    pass


class HomeScreen(Screen):
    pass


class FormScreen(Screen):
    pass


sm = ScreenManager()
sm.add_widget(LoginScreen(name='Login'))
sm.add_widget(HomeScreen(name='Home'))
sm.add_widget(FormScreen(name='Form'))


class RealApp(App):
    def build(self):
        return sm

if __name__ == '__main__':
    RealApp().run()

real.kv

#:kivy 1.10.0

<LoginScreen>:
    BoxLayout:
        Label:
            text: 'ID:'
        TextInput:
            id: LoginInputUser
            text: ''
            multiline: False
        Label:
            text: "Password:"
        TextInput:
            id: LoginInputPassword
            text: ''
            password: True
            multiline: False
        Button:
            text: 'login'
            on_press:
                if UserLogin(LoginInputUser.text, LoginInputPassword.text): LoginValidationText.text = ''
                if UserLogin(LoginInputUser.text, LoginInputPassword.text): root.manager.current = 'Home'
                else: LoginValidationText.text = 'Invalid Username or Password'
        Label:
            text: ''
            id: 'LoginValidationText'


<HomeScreen>:
    BoxLayout:
        Button:
            text: 'Logout'
            on_press:
                UserLogout()
                root.manager.current = 'Login'
        Button:
            text: 'Open Submission Form'
            on_press: root.manager.current = 'Form'
        Button:
            text: 'Shift Out' if shift == True else 'Shift In'
            on_press:
                if shift: ShiftOut()
                else: ShiftIn()


<FormScreen>:
    BoxLayout:
        Button:
            text: 'Back to menu'
            on_press: root.manager.current = 'Home'
        Label:
            text: 'Start Money:'
        TextInput:
            id: StartCash
            text: ''
            multiline: False
        Label:
            text: 'End Money:'
        TextInput:
            id: EndCash
            text: ''
            multiline: False
        Button:
            text: 'Submit'
            on_press: submitform(StartCash = int(StartCash.text), EndCash = int(EndCash.text))

Upvotes: 2

Related Questions