Calling an object from module function

Viewed 50

I have the following problem: In my main I have some objcts (currently the button and later the car). I want to acces their functions from functions in a module.

first file (main):

from tkinter import *
from tkinter import ttk
from PIL import Image, ImageTk
from buttonActions import *
from Car import car

auto = car()

root = Tk()
root.title("RemoteCar")
root.state('zoomed')

root.rowconfigure(0, weight=1)
root.rowconfigure(1,weight=1)
root.columnconfigure(0, weight=1)
root.columnconfigure(1, weight=1)


stream = ttk.Frame(root, borderwidth=5, relief="ridge")
stream.grid(row=0, column=0, rowspan=3, columnspan=2)

pil_image = Image.open("Bild.jpg")
tk_image = ImageTk.PhotoImage(pil_image)

imgLabel = Label(stream, image=tk_image)
imgLabel.pack()


keys = ttk.Frame(root ,borderwidth=5, relief="ridge")
keys.grid(row=4, column=0)

buttonWidth = 8
buttonHight = 4


button_w = Button(keys, text='W', width=buttonWidth, height=buttonHight, bg='lightgrey', command={})
button_w.grid(row=0, column=1)

root.bind('<KeyPress-w>', w_down)
root.bind('<KeyRelease-w>', w_up)

root.mainloop()

second file:

from tkinter import Button
from RemoteCarActions import *

def w_down(event):
    global button_w
    button_w.config(bg='yellow')
    w_gedrueckt()

Error Message: NameError: in w_down button_w.config(bg='yellow') name 'button_w' is not defined. Am I using global wrong or what is the problem?

2 Answers

Did you import your main file to the second one? You created an object of button in the first file, so you need to import object to the second like:

import main
main.button_w.config(bg='yellow')

For someone else: I got it working. First i tried to pass the button_w as an argument into w_down(). That didn´t work because tkinters bind() function gives the event as a argument. The solution is using lambda so both arguments are passed:

root.bind('<KeyPress-w>', lambda event, b=button_w: w_down(b))
Related