Thread: Button Clicked?

    #1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    13
    Rep Power
    0

    Question Button Clicked?


    Hello everyone,

    I have a question:

    How can a button's function run only when the button is clicked?
    I am using tkinter.

    All I want is to import(give me) the data from the user and do it with some buttons something like:

    Button1==> Keys
    Button2==> Give/Ghange Position
    Button3==> Find Keys
    Button4==> Kitchen

    So, I want when the user click on Button1(Keys)..When choose if he want to give or find the keys (Buttons 2 or 3)..and when if he clicked on Button2...give the keys' position(e.x. click on Button4) or if he clicked on Button3 print the keys position(e.x. Kitchen=Button4)

    Is it applicable or I have to import(give me) the data in another way??

    My main project is to help people who suffer from alzheimer disease.

    My code is below (in my class):

    Code:
    self.button3=Button(master,text='Keys',command=self.keyss).pack()
    self.button5=Button(master,text='Search',command=self.klik_search).pack()
    self.button4=Button(master,text='Give',command=self.klik_give).pack()
    self.button6=Button(master,text='Kitchen',command=self.kitchenn).pack()
    a={}
    if response=='Give':
       a[x]=y       # add to dictionary
      #self.lav2=Label(master,text=y).pack()
    elif response=='Search':
       for i in a:
          if i==x:
             self.lav=Label(master,text=y).pack()
    
    
    def keyss(self):
       global x
       x='Keys'
    def kitchenn(self):
       global y
       y='Kitchen'
    def klik_give(self):
       global response
       response='Give'
    def klik_search(self):
       global response
       response='Search'

    The problem is that python runs the buttons' commands before buttons clicked.So, x,y have already their values and "response" has the value of "Give" because the command is later in the code (I am not sure about this..)


    Thanks in advance.
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2005
    Posts
    618
    Rep Power
    65
    You really need to put your code in code tags to keep the proper indentations.
    Real Programmers always confuse Christmas and Halloween because Oct31 == Dec25
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    13
    Rep Power
    0
    Originally Posted by Dietrich
    You really need to put your code in code tags to keep the proper indentations.
    Done...
  6. #4
  7. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    524
    Rep Power
    34
    python runs the buttons' commands before buttons clicked.So, x,y have already their values
    Your code works fine for me (the label displays zero in the beginning). Note also that pack() returns None so there is no point in saving it.
    Code:
    from Tkinter import *
    
    class Testit(object):
        def __init__(self):
            self.x=0
            master = Tk()
            self.shared=IntVar()
            Label(master, textvariable=self.shared, bg="lightblue").pack()
            Button(master,text='Keys',command=self.keyss).pack()
            Button(master,text='Search',command=self.klik_search).pack()
            Button(master,text='Give',command=self.klik_give).pack()
            Button(master,text='Kitchen',command=self.kitchenn).pack()
    
            master.mainloop()
    
        def keyss(self):
            print "keyss called"
            self.x=1
            self.shared.set(self.x)
        def kitchenn(self):
            print "kitchenn called"
            self.x=2
            self.shared.set(self.x)
        def klik_give(self):
            print "klik_give called"
            self.x=3
            self.shared.set(self.x)
        def klik_search(self):
            print "klic_search called"
            self.x=4
            self.shared.set(self.x)
    
    T=Testit()
    Last edited by dwblas; December 9th, 2012 at 01:28 PM.
  8. #5
  9. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    13
    Rep Power
    0
    But the problem is that all I need is to return to my main program the "self.x" so then I can use it.

    Your code works fine for me
    I don't think so.That's because x,y have always the values of buttons' functions.That means that they have always the same value which can't change.


    Thanks for your reply...
  10. #6
  11. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    524
    Rep Power
    34
    self.x can and does change depending on which button is clicked. You access the variable from the calling program/function with class_instance.x (try this revised program) or with self.x if you inherit the GUI class. Take a look at "Attributes".
    Code:
    from Tkinter import *
    
    class Testit(object):
        def __init__(self):
            self.x=0
            master = Tk()
            self.shared=IntVar()
            Label(master, textvariable=self.shared, bg="lightblue", width=10).pack()
            Button(master,text='Keys',command=self.keyss).pack()
            Button(master,text='Search',command=self.klik_search).pack()
            Button(master,text='Give',command=self.klik_give).pack()
            Button(master,text='Kitchen',command=self.kitchenn).pack()
    
            master.mainloop()
    
        def keyss(self):
            print "keyss called"
            self.x=1
            self.shared.set(self.x)
        def kitchenn(self):
            print "kitchenn called"
            self.x=2
            self.shared.set(self.x)
        def klik_give(self):
            print "klik_give called"
            self.x=3
            self.shared.set(self.x)
        def klik_search(self):
            print "klic_search called"
            self.x=4
            self.shared.set(self.x)
    
    T=Testit()
    print "self.x =", T.x  ## prints whatever x is after you exit the GUI
    Last edited by dwblas; December 9th, 2012 at 02:34 PM.
  12. #7
  13. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    13
    Rep Power
    0
    Look,

    The thing that I want to do is this:

    I have 4 buttons:Keys15,Kitchen78,Search,Give/Change Position.

    The user I want to press 3 buttons e.x. "Keys15",then "Give/Change Position",then 'Kitchen78"....so, with a dictionary I am going to save the keys position like:
    Code:
    #x returns 'Keys' from 'Keys15' Button's function
       #y returns 'Kitchen' from 'Kitchen78' Button's function
       dict[x]=y
    Otherwise,
    if the user clicked on : Keys15-->Search-->Kitchen78....I want to search the 'Keys' (x) position..like
    Code:
     for i in dict.keys():
           if i==x:
               mylabel1=Label(master,text=y).grid(row=10,column=20)
    But the the only way to do this is to Check if "response" variable (which returns from "Search" or "Give/Change Position" Buttons' function) is "search" or "give".

    I have this code:

    Code:
    from Tkinter import *
    class App:
     
        def __init__(self, master):
            global x,y,response
            def Keys15():
                global x
                x="Keys"
            def Kitchen78():
                global y
                y="Kitchen"
            def Give_Change():
                global response
                response='Give'
            def Search():
                global response
                response='Search'
            self.butsf=Button(master,text='Quit',command=master.quit).grid(row=1,column=1)   
            self.but785 = Button(master, text="Keys15",command=Keys15).grid(row=40,column=50)
            self.but562=Button(master,text='Give/Change Position',command=Give_Change).grid(row=50,column=50)
            self.but7894=Button(master,text='Search',command=Search).grid(row=60,column=50)
            self.but40=Button(master, text='Kitchen78', command=Kitchen78).grid(row=70,column=50)
            a={}
            if response=='Give':
                a[x]=y
            elif response=='Search':
                for i in a.keys():
                    if i==x:
                        mlavt785=Label(master,text='The'+str(x)+'are in the'+str(y)).grid(row=80,column=50)
            
            
            
    global x,y,response
    root = Tk()
    app = App(root)
    root.mainloop()
    But gives me an error like 'global name 'response' is not defined'..

    Else,If I use:
    Code:
     While True:
        try:
            if response=='Give':
                a[x]=y
                break
            elif response=='Search':
                for i in a.keys():
                    if i==x:
                        mlavt785=Label(master,text='The'+str(x)+'are in the'+str(y)).grid(row=80,column=50)
                break
        except:
           print 'Error'
    It is an endless loop.

    **I think that i can use x,y,response only after press "Quit" button** Why??

    Can you help me with the way I have to follow in my class..?
    Help Please....
  14. #8
  15. No Profile Picture
    Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    May 2009
    Posts
    524
    Rep Power
    34
    I am not sure what you want in the end, but you might want to use checkbuttons as you can then easily tell which are checked and which are not.. This is one of the standard Tkinter examples.
    Code:
        import Tkinter as tk     # Python2
    except ImportError:
        import tkinter as tk     # Python3
    .
    def cb_checked():
        # show checked check button item(s)
        label['text'] = ''
        for ix, item in enumerate(cb):
            if cb_v[ix].get():
                label['text'] += '%s is checked' % item['text'] + '\n'
    
    root = tk.Tk()
    .
    cb_list = [
    'apple',
    'orange',
    'banana',
    'pear',
    'apricot'
    ]
    .
    # list(range()) needed for Python3
    # list of each button object
    cb = list(range(len(cb_list)))
    # list of IntVar for each button
    cb_v = list(range(len(cb_list)))
    for ix, text in enumerate(cb_list):
        # IntVar() tracks checkbox status (1=checked, 0=unchecked)
        cb_v[ix] = tk.IntVar()
        # command is optional and responds to any cb changes
        cb[ix] = tk.Checkbutton(root, text=text,
                                variable=cb_v[ix], command=cb_checked)
        cb[ix].grid(row=ix, column=0, sticky='w')
    .
    label = tk.Label(root, width=20)
    label.grid(row=ix+1, column=0, sticky='w')
    .
    # you can preset check buttons (1=checked, 0=unchecked)
    cb_v[3].set(1)
    # show initial selection
    cb_checked()
    .
    root.mainloop()
    Also, you can disable a button after it is clicked
    Code:
    from Tkinter import *
    
    class Testit(object):
        def __init__(self):
            self.x=0
            master = Tk()
            self.shared=IntVar()
            Label(master, textvariable=self.shared, bg="lightblue", width=10).pack()
            self.b1=Button(master,text='Keys',command=self.keyss)
            self.b1.pack()
            self.b2=Button(master,text='Search',command=self.klik_search)
            self.b2.pack()
            self.b3=Button(master,text='Give',command=self.klik_give)
            self.b3.pack()
            self.b4=Button(master,text='Kitchen',command=self.kitchenn)
            self.b4.pack()
    
            master.mainloop()
    
        def common_funct(self, button, set_x):
            self.x=set_x
            self.shared.set(self.x)
            button.config(bg="lightgray")
            button.config(state=DISABLED)
    
        def keyss(self):
            print "keyss called"
            self.common_funct(self.b1, 1)
    
        def kitchenn(self):
            print "kitchenn called"
            self.common_funct(self.b4, 4)
    
        def klik_give(self):
            print "klik_give called"
            self.common_funct(self.b3, 3)
    
        def klik_search(self):
            print "klic_search called"
            self.common_funct(self.b2, 2)
    
    T=Testit()
  16. #9
  17. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Dec 2012
    Posts
    13
    Rep Power
    0
    I am not sure what you want in the end
    hahaha...Sorry for confusing you.
    Let's Start again.

    My project is to help people who suffer from alzheimer disease.

    My main object is to help whose people about the lack in their memory.So,I want to give me first the position of their things(e.x. keys) and then everytime they want their things program can give their position.
    For example:
    The program may have a lot of things (keys,umbrella,id,glasses etc)...
    and certain rooms (kitchen,bathroom,living room etc)..
    Also,must have option like ("Give" or "Search" ..the position)....
    So, I want to save the position or print (in a label)...what the user wants..using a dictionary..

    If he choose Keys-->Give-->Kitchen...I have to save the keys in the kitchen (in the dictionary)
    else...if he choose Keys-->Search...I have to search in the dictionary the Keys position and print it in a label.

    In which way I have to do this...?
    Using buttons/checkbuttons...something else..?

    Thanks...

IMN logo majestic logo threadwatch logo seochat tools logo