Python Forum
[Tkinter] Tkinter newly created button does not execute command
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Tkinter newly created button does not execute command
#1
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()
Reply
#2
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
Reply
#3
(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.
Reply
#4
It worked on my system
Reply
#5
(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
Reply
#6
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.
Reply
#7
Post the new code that you are now using.
Reply
#8
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tkinter] TKinter Remove Button Frame Nu2Python 8 978 Jan-16-2024, 06:44 PM
Last Post: rob101
  tkinter - touchscreen, push the button like click the mouse John64 5 845 Jan-06-2024, 03:45 PM
Last Post: deanhystad
  Centering and adding a push button to a grid window, TKinter Edward_ 15 4,730 May-25-2023, 07:37 PM
Last Post: deanhystad
  tkinter.TclError: can't invoke "canvas" command cybertooth 8 5,976 Feb-23-2023, 06:58 PM
Last Post: deanhystad
  Can't get tkinter button to change color based on changes in data dford 4 3,418 Feb-13-2022, 01:57 PM
Last Post: dford
  [Tkinter] Button 'command' Argument Confusion gw1500se 11 5,861 Nov-11-2021, 08:45 PM
Last Post: menator01
  Creating a function interrupt button tkinter AnotherSam 2 5,526 Oct-07-2021, 02:56 PM
Last Post: AnotherSam
  [Tkinter] Have tkinter button toggle on and off a continuously running function AnotherSam 5 5,008 Oct-01-2021, 05:00 PM
Last Post: Yoriz
  tkinter showing image in button rwahdan 3 5,623 Jun-16-2021, 06:08 AM
Last Post: Yoriz
  Continue command in python tkinter? MLGpotato 7 8,473 Mar-27-2021, 04:59 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020