Unable to call child function via tkinter button in python

Viewed 33

In GUI, when I click step1 button it is assign value to self.p1 then I click step2 which should call child function which will use self.p1 value generated from step1.

But I am getting error at step 2, if i use instance then it executing step1 even before clicking the button.

import tkinter
from tkinter import *

def neighbor():

    n1 = datetime.datetime.now()
    print("n1",n1)
    return n1

class Parent:
    def __init__(self):
        self.p1 = neighbor()
        print("p1",self.p1)

    def child(self):
        print("c1", self.p1)

root=tkinter.Tk()
root.title("test")
root.geometry("400x300")

#instance = parent()
#instance.child()

b=Button(root,text='step1',bg='green',command=Parent,fg='red',width=10,height=3,font=('Times new Roman',20))
b.grid(column=4,row=5)

d=Button(root,text='step2',bg='green',command=Parent.child,fg='red',width=10,height=3,font=('Times new Roman',20))
d.grid(column=4,row=6)

root.mainloop()
1 Answers

The callback for step1 should create a global instance of Parent which the callback for step2 can access.

def step1_callback():
    global p
    p = Parent()

def step2_callback():
    if p is not None:
        p.child()


p = None

b = Button(root, text='step1', bg='green', command=step1_callback, fg='red', width=10, height=3, font=('Times new Roman',20))

d = Button(root, text='step2', bg='green', command=step2_callback, fg='red', width=10, height=3, font=('Times new Roman',20))
Related