473,414 Members | 1,606 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,414 software developers and data experts.

Tkinter event handlers and command callbacks

Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. fields = 'Name', 'Job', 'Pay'
  3.  
  4. def fetch(event,entries):
  5.    for entry in entries:
  6.        print 'Input => "%s"' % entry.get()       # get text
  7.        print  event.widget 
  8.  
  9.  
  10. def makeform(root, fields):
  11.    entries = []
  12.    for field in fields:
  13.        row = Frame(root)                           # make a new row
  14.        lab = Label(row, width=5, text=field)       # add label, entry
  15.        ent = Entry(row)
  16.        row.pack(side=TOP, fill=X)                  # pack row on top
  17.        lab.pack(side=LEFT)
  18.        ent.pack(side=RIGHT, expand=YES, fill=X)    # grow horizontal
  19.        entries.append(ent)
  20.    return entries
  21.  
  22. if __name__ == '__main__':
  23.    root = Tk()
  24.    ents = makeform(root, fields)
  25.    root.bind('<Return>', lambda event,entries=ents: fetch(event,entries))       
  26.    Button(root, text='Fetch', command= lambda event:fetch(event,entries)).pack(side=LEFT)  # #how to revise it?
  27.    root.mainloop()
  28.  
in the code ,the bind method is ok, how to revise "command=lambda event:fetch(event,entries)",to make it work too??
Aug 23 '11 #1

✓ answered by luofeiyu

Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2.  
  3. def fetch(x):
  4.            print x, type(x)
  5.  
  6. if __name__ == '__main__':
  7.            root = Tk()
  8.            button=Button(root,text='Fetch')
  9.            button.pack()
  10.            button.focus_set()
  11.            button.grab_set()
  12.            button.bind('<Return>',fetch)       
  13.            root.mainloop() 
add button.grab_set(),it's ok now

7 3985
bvdet
2,851 Expert Mod 2GB
The button command callback does not receive an argument. If you want the button to respond to an event and the callback receive the event as an argument, bind an event to it, possibly "<ButtonRelease-1>".
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. fields = 'Name', 'Job', 'Pay'
  3.  
  4. def fetch(entries, event=None):
  5.    for entry in entries:
  6.        print 'Input => "%s"' % entry.get()       # get text
  7.        if event:
  8.            print  event.widget 
  9.  
  10.  
  11. def makeform(root, fields):
  12.    entries = []
  13.    for field in fields:
  14.        row = Frame(root)                           # make a new row
  15.        lab = Label(row, width=5, text=field)       # add label, entry
  16.        ent = Entry(row)
  17.        row.pack(side=TOP, fill=X)                  # pack row on top
  18.        lab.pack(side=LEFT)
  19.        ent.pack(side=RIGHT, expand=YES, fill=X)    # grow horizontal
  20.        entries.append(ent)
  21.    return entries
  22.  
  23. if __name__ == '__main__':
  24.    root = Tk()
  25.    ents = makeform(root, fields)
  26.    root.bind('<Return>', lambda event, entries=ents: fetch(entries, event))
  27.    Button(root, text='Fetch', command=lambda:fetch(ents)).pack(side=LEFT)  # #how to revise it?
  28.    root.mainloop()
Aug 23 '11 #2
dwblas
626 Expert 512MB
First, your title makes this thread appear to be a "HowTo", i.e. code that explains how to do something, so you may get fewer readers/respondents as a result.
how to revise "command=lambda event:fetch(event,entries)",to make it work too??
What does this mean? If you mean that your want to pass something to a function when a button is pressed, Python provides "partial". Note that Guido does not like lambda, and planned to remove it in Python 3 as there are better ways to do things. Also, in the fetch() function, you print the same event for each entry in entries. It should be indented at the same level as the for() statement so it only prints once.
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2. from functools import partial
  3.  
  4. def fetch(event, entries):
  5.        for entry in entries:
  6.            print 'Input => "%s"' % entry.get()       # get text
  7.            if event:
  8.                print  event.widget 
  9.  
  10.  
  11. def makeform(root, fields):
  12.        entries = []
  13.        for field in fields:
  14.            row = Frame(root)                           # make a new row
  15.            lab = Label(row, width=5, text=field)       # add label, entry
  16.            ent = Entry(row)
  17.            row.pack(side=TOP, fill=X)                  # pack row on top
  18.            lab.pack(side=LEFT)
  19.            ent.pack(side=RIGHT, expand=YES, fill=X)    # grow horizontal
  20.            entries.append(ent)
  21.        return entries
  22.  
  23. if __name__ == '__main__':
  24.        fields = 'Name', 'Job', 'Pay'
  25.        root = Tk()
  26.        ents = makeform(root, fields)
  27.  
  28.        ## this can be converted to "partial" as well if you want
  29.        root.bind('<Return>', lambda event, entries=ents: fetch(entries, event))
  30.  
  31.        xb =Button(root, text='Fetch')
  32.        xb.pack(side=LEFT)
  33.  
  34.        ## note that both 'root' & 'xb' bind an object to an event
  35.        ## that is sent to the function
  36.        xb.bind("<Button-1>", partial(fetch, entries=ents))
  37.        root.mainloop() 
Aug 23 '11 #3
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2.  
  3. def fetch(x):
  4.        print  x.type,x
  5.  
  6.  
  7. if __name__ == '__main__':
  8.        root = Tk()
  9.        root.bind('<Return>', fetch)
  10.        root.mainloop()
  11.  
i can get output :
2 <Tkinter.Event instance at 0xb742986c>

Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2.  
  3. def fetch(x):
  4.        print  x.type,x
  5.  
  6.  
  7. if __name__ == '__main__':
  8.        root = Tk()
  9.        button=Button(root,text='Fetch')
  10.        button.pack()
  11.        button.bind('<Return>',fetch)       
  12.        root.mainloop()
  13.  
why i can get nothing when i click enter??
Aug 24 '11 #4
dwblas
626 Expert 512MB
To capture a "Return", you have to set the focus. Otherwise, the focus is not set on the widget so the Return goes to the root window or whatever has focus, and you don't have any bindings for it.
Expand|Select|Wrap|Line Numbers
  1. rom Tkinter import *
  2.  
  3. def fetch(x):
  4.        print x, type(x)
  5.  
  6. if __name__ == '__main__':
  7.        root = Tk()
  8.        button=Button(root,text='Fetch')
  9.        button.pack()
  10.        button.focus_set()
  11.        button.bind('<Return>',fetch)       
  12.        root.mainloop() 
Aug 24 '11 #5
you lose f in rom (it is from),i made a try,it'ok,but there is still a problem,
when i finish my first enter,it's ok,there is output ,
when i have a try for the second time ,there is no output??
Aug 24 '11 #6
bvdet
2,851 Expert Mod 2GB
Are you losing focus after the first event? You can reset the focus in the callback with x.widget.focus_set()
Aug 24 '11 #7
Expand|Select|Wrap|Line Numbers
  1. from Tkinter import *
  2.  
  3. def fetch(x):
  4.            print x, type(x)
  5.  
  6. if __name__ == '__main__':
  7.            root = Tk()
  8.            button=Button(root,text='Fetch')
  9.            button.pack()
  10.            button.focus_set()
  11.            button.grab_set()
  12.            button.bind('<Return>',fetch)       
  13.            root.mainloop() 
add button.grab_set(),it's ok now
Aug 25 '11 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: Matthias Kaeppler | last post by:
Hi, in my program, I have this funtion to compute the sum of a bunch of files: Glib::ustring DirBrowser::get_total_file_size() { using namespace boostfs; // boostfs = boost::filesystem using...
3
by: rammel | last post by:
hi, can't I call member functions from an placeholder of a boost-like lambda expression? look on the example below please: -----------------------------------------------------------...
15
by: Matt | last post by:
Hi There, Can anyone explain me the real advantages of (other than syntax) lambda expressions over anonymous delegates? advantage for one over the other. delegate int F(int a); F fLambda = a...
2
by: =?Utf-8?B?UnV0aCBNYXJr?= | last post by:
Hey, Am trying to write a lambda expression for a delegate, am getting an error as ------------------------------ only assignment, call, increment, decrement, and new expression can be used as...
0
by: sneha0608 | last post by:
I am using LINQ.I want to dynamically build a lambda expression which would be passed to the where clause of the Query. i have written the following code: ParameterExpression param =...
5
by: Satish | last post by:
When i compile this function I get the error Cannot convert lambda expression of type System.delegate because it is not a delegate type. private void SetStatus(string status) { if...
8
by: Simon Woods | last post by:
Hi A blog post I was reading (http://www.defmacro.org/ramblings/fp.html) included this lambda function. Function makeIncrementer() { int n = 0; int increment() { return ++n;
15
by: K Viltersten | last post by:
I've got a hint from a gentleman here to use the following syntax. public static FileInfo GetFilesRegExp(this DirectoryInfo di, string pat) { Regex re = new Regex(pat); return Array.FindAll(...
3
by: Marc Gravell | last post by:
A lambda expression is a short form to write a delegate In /this/ case (LINQ-to-Objects): yes - but it could equally be compiled to an Expression, which is very, very different. A lambda...
2
by: Colin Han | last post by:
Hi, all, If I write follow code in c# method. The IDE will compile it to a complex construct method of System.Linq.Expression. Expression<Func<int>ex = () =10; will be compile to:...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.