Python Forum

Full Version: Tkinter newly created button does not execute command
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello all,

I have got this code which should open a GUI with two buttons, one saying Hello, the other one QUIT which it does. When QUIT button is pressed the application should close which it does, and when Hello button is pressed new button should be gridded onto the application in a row number 1 and also disable a Hello button. And when newly gridded button is pressed it should delete itself of the grid and reactivate Hello button, but for some reason, it does not do that. Any ideas why?



from tkinter import *

class Application(Frame):
    
    def new_button(self):
        print("enable_b")
        self.hi_there.config(state=ACTIVE)
        self.new_button.grid_remove()
        
    def say_hi(self):
        print("hi there, everyone!")
        self.new_button = Button(self)
        self.new_button["text"] = "New BTN"
        self.new_button.grid(row=1,column=0)
        self.hi_there.config(state=DISABLED, command=self.new_button)

    def createWidgets(self):
        self.QUIT = Button(self)
        self.QUIT.config(text="QUIT",fg="red",command=self.quit)
        self.QUIT.grid(row=0,column=1)
        self.hi_there = Button(self)
        self.hi_there["text"] = "Hello",
        self.hi_there["command"] = self.say_hi
        self.hi_there.grid(row=0,column=0)

    def __init__(self, master=None):
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

root = Tk()
app = Application(master=root)
app.mainloop()
root.destroy()
You need to provide a quit method:
from tkinter import *
 
class Application(Frame):
    def __init__(self, master=None):
        self.master = master
        self.master.geometry('300x100+10+10')
        Frame.__init__(self, master)
        self.pack()
        self.createWidgets()

    def new_button(self):
        print("enable_b")
        self.hi_there.config(state=ACTIVE)
        self.new_button.grid_remove()
         
    def say_hi(self):
        print("hi there, everyone!")
        self.new_button = Button(self)
        self.new_button["text"] = "New BTN"
        self.new_button.grid(row=1,column=0)
        self.hi_there.config(state=DISABLED, command=self.new_button)
 
    def createWidgets(self):
        self.QUIT = Button(self)
        self.QUIT.config(text="QUIT",fg="red",command=self.quit)
        self.QUIT.grid(row=0,column=1)
        self.hi_there = Button(self)
        self.hi_there["text"] = "Hello",
        self.hi_there["command"] = self.say_hi
        self.hi_there.grid(row=0,column=0)

    def quit(self):
        self.master.destroy()

def testit(): 
    root = Tk()
    app = Application(master=root)
    app.mainloop()

if __name__ == '__main__':
    testit()

I also moved the __init__ routine to top (will work elsewhere, but other programmers will always look for it at the top)
added startup code 'if __name__ ...'
and created class variable for delete
(Jul-20-2018, 09:03 AM)Larz60+ Wrote: [ -> ]You need to provide a quit method:

I also moved the __init__ routine to top (will work elsewhere, but other programmers will always look for it at the top)
added startup code 'if __name__ ...'
and created class variable for delete

I'm not sure if you got the problem right. QUIT button works perfectly with the original code. What does not work is the newly gridded button does not execute a function called new_button which should reactivate hello button and remove new button of the grid.
It worked on my system
(Jul-20-2018, 09:44 AM)Larz60+ Wrote: [ -> ]It worked on my system

And when you pressed New Button console printed "enable_b"? And Hello button got reactivated if I got right?

(Jul-20-2018, 09:44 AM)Larz60+ Wrote: [ -> ]It worked on my system

Please check the video. It shows that when the new button generated is clicked it is not reactivating the Hello button.

https://www.useloom.com/share/59c063c99d...b83d4bc3d9
You can't ask us to open random videos. With the number of posts that we look at and answer each day, that is an unusual request, asking more than most of us are willing to do.

Please remember that moderators and admins are volunteers.
Post the new code that you are now using.
Hello everyone
Can someone help me with the following:
I have a code with three buttons, two buttons read a data spectrum and find the number of peaks of each. Each function that is called returns the number of peaks.

A third button should verify a comparison between these two data that are returned (number of peaks in each spectrum). However I do not know how to set the parameters to the function when it must be invoked from the third button.

Will someone have a similar code?

This is the code

def load_ctrl():
path=StringVar()
filename = tkFileDialog.askopenfilename(initialdir = "/home/pi/Desktop/Programas",title = "Select file",filetypes = (("Text files","*.txt"),("all files","*.*")))
shift = open("XAcetominofeno.txt") #XCiprofloxacino, XAcetominofeno
path=filename
c1 = shift.read()
d1 = c1.split()
datos1 = []
for i in d1:
datos1.append(float(i))
intensity = open(path)

c2 = intensity.read()
d2 = c2.split()
datos2 = []
for i in d2:
datos2.append(float(i))

#---------------DETECCION DE PICOS------------------------------

indexes1 = scipy.signal.find_peaks_cwt(datos2, np.arange(3, 5),
max_distances=np.arange(2, 5)*10)
indexes1 = np.array(indexes1) - 1
length_a=len(indexes1)
dx=[]
dy=[]

plt.figure('Raman spectrum')
plt.xlim(100,1800)
plt.axes()
plt.grid()
plt.xlabel('Raman Shift (cm-1)')
plt.ylabel('Intnesity (a.u)')
plt.plot(datos1, datos2,'r-')
for j in range(length_a):
a=indexes1[j]
dx=datos1[a]
dy=datos2[a]
plt.plot(dx, dy,'b*')
plt.show()
return length_a

#----------DEFINIENDO FUNCIONES DE DRUG TEST-------------

def load_drug():
pathx=StringVar()
filenamex = tkFileDialog.askopenfilename(initialdir = "/home/pi/Desktop/Programas",title = "Select file",filetypes = (("Text files","*.txt"),("all files","*.*")))
shift = open("XCiprofloxacino.txt") #XCiprofloxacino, XAcetominofeno
pathx=filenamex
c1 = shift.read()
d1 = c1.split()
datos11 = []
for i in d1:
datos11.append(float(i))
intensity = open(pathx)
c2 = intensity.read()
d2 = c2.split()
datos22 = []
for i in d2:
datos22.append(float(i))

#---------------DETECCION DE PICOS------------------------------

indexes2 = scipy.signal.find_peaks_cwt(datos22, np.arange(3, 5),
max_distances=np.arange(2, 5)*10)
indexes2 = np.array(indexes2) - 1
length_b=len(indexes2)
dx=[]
dy=[]

plt.figure('Raman spectrum')
plt.xlim(100,1800)
plt.axes()
plt.grid()
plt.xlabel('Raman Shift (cm-1)')
plt.ylabel('Intnesity (a.u)')
plt.plot(datos11, datos22,'b-')
for k in range(length_b):
a=indexes2[k]
dx=datos11[a]
dy=datos22[a]
plt.plot(dx, dy,'r*')
plt.show()
return length_b

#----------DEFINIENDO FUNCIONES DE TEST------------------

def test_drug(v,length_a,length_b):
if length_a>length_b:
print "NO PASS"
msge=Label(v,text="NO PASS",fg="red",height=2,font="Helvetica 14 bold").place(x=40,y=312)
else:
print "PASS"
msge=Label(v,text="PASS",fg="green",height=2,font="Helvetica 14 bold").place(x=48,y=312)

return



#-------------------DEFINIENDO BOTONES-------------------


loadctrl=Button(v,text="Load Reference",font=buttom_p,fg="black",height=2,width=12,command=load_ctrl).place(x=16,y=90)
loadsample=Button(v,text="Drug test",font=buttom_p,fg="black",height=2,width=12, command=load_drug).place(x=16,y=143)
sampletest=Button(v,text="Test",font=buttom_p,fg="black",height=2,width=12, command=lambda:test_drug(v,21,5)).place(x=16,y=195)
start=Button(v,text="Initialize",font=buttom_p,fg="black",height=2,width=12,command=set_globalvar).place(x=16,y=248)
exit=Button(v,text="Exit",font=exit_p,fg="red",height=3,width=10, command=v.quit).place(x=18,y=360)
v.mainloop()