Re: Functions vs OOP
On 9/4/2011 9:13 AM, rusi wrote: On Sep 3, 9:15 pm, William Gillnore...@domain.invalid wrote: During some recent research, and re-familiarization with Python, I came across documentation that suggests that programming using functions, and programming using objects were somehow opposing techniques. Staying with (for the moment) the suggestion that OO-P and F-P are complementary, I believe it is worthwhile to distinguish syntactic OO- P vs F-P from semantic OO-P vs F-P. Syntactically: f(x) is functional x.f() is object oriented. Semantically if f's return value depends only on x ie does not depend on state it is functional (in the math sense) -- the jargon is that f is referentially transparent. Not to split hairs, but syntactically f(x) is a function in many programming paradigms. As I understand it functional programming places specific requirements on functions, i.e.referential transparency. So f(x) may or may not be functional. x.f() is also a function, but it is a member of the object x, is referred to as a 'method' of x, and uses the syntactical dot notation objectdotfunction for identification. Referential opaqueness is usually such a source of problems that it turns out good to contain the problem somewhat -- hence the wish for encapsulation. One can find in the python library itself all 4 combinations: syntactically and semantically OO : sort syntactically and semantically FP: sorted syntactically OO semantically FP: join -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions vs OOP
On 9/3/2011 12:25 PM, Steven D'Aprano wrote: William Gill wrote: Are they suggesting that any function that takes an object as an argument should always be a method of that object? Yes. I can think of times when a special application, such as a converter, would take an object as an argument, but the somewhat unique nature of the application wouldn't justify changing the class to make the behavior into a method. I could extend the underlying class to include the new behavior (method), but that would mean existing instances of the base class would need conversion to the new class, requiring yet another method. Seems to me, that would be POOP (Puristic Object Oriented Programming) ;-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions vs OOP
On 9/5/2011 3:04 PM, Jean-Michel Pichavant wrote: William Gill wrote: Not to split hairs, but syntactically f(x) is a function in many programming paradigms. As I understand it functional programming places specific requirements on functions, i.e.referential transparency. So f(x) may or may not be functional. x.f() is also a function, but it is a member of the object x, is referred to as a 'method' of x, and uses the syntactical dot notation objectdotfunction for identification. Functional programming is not about writing a programm with functions snip. This may cause some confusion. It can, and it did. That was the impression I (incorrectly) got from the documentation. Which didn't make sense to me. (google it for more info). I can, and I did. That, and the answers I got in this ng are how I corrected my misconception. Your original post was about functions vs methods, which are identical except some syntax detail. FYI, in python x.f() is equivalent to f(x). In an OOP world one will prefer the x.f() form. No, my original post was about how (based on the aforementioned misconception) the documentation seemed to suggest that OOP should never have free standing functions, only methods. -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions vs OOP
On 9/4/2011 2:32 PM, Terry Reedy wrote: On 9/4/2011 4:13 AM, tinn...@isbd.co.uk wrote: Ian Kellyian.g.ke...@gmail.com wrote: Functional programming is about using functions in the *mathematical* sense. A mathematical function maps one value (or tuple of values) to another value. The mapped value never varies; if it did, it would be a different function. So functional programming eschews the use of functions where the results depend on any internal or external state beyond the values of the passed-in arguments, such as the variable state of the object the method is being called on. I think there may be another issue here. If someone says functional programming to me then I would generally assume that they *do* mean programming using functions. While your distinction of the two may be strictly correct I don't think it's the generally accepted meaning. The distintion drawn by Ian *is* generally accepted in computer science. See https://secure.wikimedia.org/wikipedia/en/wiki/Functional_programming For instance, programming is C is imperative programming with functions but it generally is not 'functional programming' in the sense referred to by Ian and the Wikipedia article. Given that our docs are written by people who do understand the technical distinction, you are probably wrong to assume otherwise. However, as I said to William, it is possible that our docs could be improved so as to not depend on all readers having prior knowledge of the intended meaning of 'functional programming'. As the use of Python has expanded, so has the variety of backgrounds of Python programmers. Since I am the one who opened this can of worms, and since I believe I have relocated the document that I misinterpreted, I feel compelled to jump in here. The source of my error is Functional Programming HOWTO (/python-3.1.3-docs-html/howto/functional.html) Having arrived at this page indirectly (searching for and skimming other information regarding functions and methods) I was only half paying attention. As a result I made the same mistake Chris did. As a point of reference, I would not call myself a programmer, and any formal exposure was many, many years ago. I am familiar with the concepts of procedural, declarative, and object-oriented programming, but not functional. At least not in this context. Having done a little more digging I now understand the difference. Functional programming is the proper terminology, and had I come across it from another direction, or with a more deliberate focus I probably wouldn't have made the initial mistake. If you read the material with even a nominal understanding of the functional paradigm (functional relationships in a mathematical sense, not functions in the procedural sense), it is clear. If you read it without consciously recognizing this difference, the material does nothing to alert you to the initial error. -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions vs OOP
On 9/4/2011 7:41 PM, Steven D'Aprano wrote: William Gill wrote: The source of my error is Functional Programming HOWTO (/python-3.1.3-docs-html/howto/functional.html) For those who don't have access to William's local file system, I expect he's looking at this: http://docs.python.org/release/3.1.3/howto/functional.html or the most recent version: http://docs.python.org/dev/howto/functional.html I didn't expect anyone to access my file system so I trimmed the path, but left enough for an industrious soul like yourself to figure it out. You did, so it seems I was correct, or do you think functional.html would have been sufficient? ;-) [...] If you read the material with even a nominal understanding of the functional paradigm (functional relationships in a mathematical sense, not functions in the procedural sense), it is clear. If you read it without consciously recognizing this difference, the material does nothing to alert you to the initial error. What about the entire Introduction section, which starts with this statement? This section explains the basic concept of functional programming Which clears up the misunderstanding, how? Unless the target audience is people who already understands the basic concept of functional programming. That seems like a circular reference. The article is introducing a concept. To assume any familiarity with that concept as a basis, is not an introduction. As previously stated; I was already familiar with the concepts of procedural, declarative, and object-oriented programming, but not functional programming. Nothing I read (I'll be honest; scanned) did anything to contradict my incorrect point of reference. If you would like to suggest improvements, please do so. How about a caveat stating something like NOTE: functional as in mathematical functions, not to be confused with functions/procedures. -- http://mail.python.org/mailman/listinfo/python-list
Functions vs OOP
During some recent research, and re-familiarization with Python, I came across documentation that suggests that programming using functions, and programming using objects were somehow opposing techniques. It seems to me that they are complimentary. It makes sense to create objects and have some functions that take those objects as arguments. Are they suggesting that any function that takes an object as an argument should always be a method of that object? Conversely I can see creating functions that take raw input (e.g. strings) and return it in a format compatible with an object's constructor, rather than have objects accept any conceivable format for its constructor. Am I missing something, or am I taking things too literally? -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions vs OOP
On 9/3/2011 12:29 PM, MRAB wrote: I think you mean complementary. :-) How polite of you to point out my spelling deficiency. I guess shouldn't be watching football while typing (I'm sure the beer didn't help either). I think that it's all about state. In functional programming, there's no state; a function's result depends solely on its arguments, so it will always return the same result for the same given arguments. In OOP, on the other hand, an object often has a state; a method may return a different result each time it's called, even for the same given arguments. I think you mean it [sic, a function] will return the same result for the same given values... x=1 y= myFn(x) will return the same result as y= myFn(1) A method may use an attribute as an implicit argument, and that attribute's value change, just like the value of x (above) may change. It may or may not return anything (it may just modify an attribute). The question wasn't about encapsulation, it was about programming paradigms, and if they conflict. As was pointed out elsewhere, I may have just confused functional programming with programming using functions. -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions vs OOP
On 9/3/2011 2:50 PM, Ian Kelly wrote: I think you may be confusing functional programming and programming using functions. These are not the same thing. I think you may be right, Ian. It didn't make much sense -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions vs OOP
On 9/3/2011 3:15 PM, Terry Reedy wrote: William Gill wrote: During some recent research, and re-familiarization with Python, I came across documentation Ours, or someone else's? Python. Since in Python, everything is an object, that would mean that every function has to be a method, which would mean creating classes just to have a class to attach functions to. How awful. Exactly why I asked, but I realize the the mistake was mine. I think they were talking about functional programming not using functions in an OO program. -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions vs OOP
On 9/3/2011 5:39 PM, Ben Finney wrote: William Gillnoreply@domain.invalid writes: On 9/3/2011 3:15 PM, Terry Reedy wrote: William Gill wrote: During some recent research, and re-familiarization with Python, I came across documentation Ours, or someone else's? Python. Can you show exactly where in the Python documentation you found the passage which confused you? Sorry, no. I tried to locate the exact reference again, and couldn't remember where I read it (short term memory problems). -- http://mail.python.org/mailman/listinfo/python-list
Re: Functions vs OOP
On 9/3/2011 9:51 PM, Terry Reedy wrote: It is possible that our doc was less than crystal clear. We are constantly improving it where we can see fixable faults. If you run across whatever it was and it still seems a bit muddy, post something again. Will do. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help parsing a text file
On 9/1/2011 1:58 PM, JT wrote: On Monday, August 29, 2011 1:21:48 PM UTC-5, William Gill wrote: I have a text file with XML like records that I need to parse. By XML like I mean records have proper opening and closing tags. but fields don't have closing tags (they rely on line ends). Not all fields appear in all records, but they do adhere to a defined sequence. lxml can parse XML and broken HTML (see http://lxml.de/parsing.html). - James Thanks to everyone. Though I didn't get what I expected, it made me think more about the reason I need to parse these files to begin with. So I'm going to do some more homework on the overall business application and work backward from there. Once I know how the data fits in the scheme of things, I will create an appropriate abstraction layer, either from scratch, or using one of the existing parsers mentioned, but I won't really know that until I have finished modeling. -- http://mail.python.org/mailman/listinfo/python-list
Help parsing a text file
I haven't done much with Python for a couple years, bouncing around between other languages and scripts as needs suggest, so I have some minor difficulty keeping Python functionality Python functionality in my head, but I can overcome that as the cobwebs clear. Though I do seem to keep tripping over the same Py2 - Py3 syntax changes (old habits die hard). I have a text file with XML like records that I need to parse. By XML like I mean records have proper opening and closing tags. but fields don't have closing tags (they rely on line ends). Not all fields appear in all records, but they do adhere to a defined sequence. My initial passes into Python have been very unfocused (a scatter gun of too many possible directions, yielding very messy results), so I'm asking for some suggestions, or algorithms (possibly even examples)that may help me focus. I'm not asking anyone to write my code, just to nudge me toward a more disciplined approach to a common task, and I promise to put in the effort to understand the underlying fundamentals. -- http://mail.python.org/mailman/listinfo/python-list
Re: Help parsing a text file
On 8/29/2011 2:31 PM, Philip Semanchuk wrote: If the syntax really is close to XML, would it be all that difficult to convert it to proper XML? Then you have nice libraries like ElementTree to use for parsing. Possibly, but I would still need the same search algorithms to find the opening tag for the field, then find and replace the next line end with a matching closing tag. So it seems to me that the starting point is the same, and then it's my choice to either process the substrings myself or employ something like ElementTree. -- http://mail.python.org/mailman/listinfo/python-list
Re: simple games w/o pygame
Thanks everyone. These references will help greatly. I was about to take some javascript examples and rewrite them in Python. -- http://mail.python.org/mailman/listinfo/python-list
simple games w/o pygame
I am teaching an 11 year old who wants to learn programming. I chose Python, and it is working well. I seem to remember lots of simple script games, like quizzes, number games etc. that would be good for his tutorial. However, now all I can find is more complex games using Pygame. Can anyone help me out here? -- http://mail.python.org/mailman/listinfo/python-list
python script to act as list server
Before I spend the next couple weeks researching and testing, can anyone tell me if what I want to do is possible, and possibly point me in the right direction to get started. I want to forward any email addressed to [EMAIL PROTECTED] to a python script that will forward it to all the other subscribers,but does not reveal the sender's email address. Instead the return address will be [EMAIL PROTECTED] That way people will be able to have an e-mail based chat group w/o revealing their email address. Sounds simple enough to me, but sounding and implementing can be vastly different animals :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: smtp server simulation using Python
Dave Borne wrote: I have a (web) development computer w/o an SMTP server and want to test form generated e-mail using a dummy SMTP server that delivers the mail message to a file, or better yet, to a text editor instead of actually sending it. Here's a quick and dirty script I use this for email testing purposes - it's windows specific, but that's easy enough to change. Actually XP is where I need it. Thanks Bill import smtpd, os, time, asyncore class mailserver(smtpd.SMTPServer): def __init__(self): smtpd.SMTPServer.__init__(self, ('',25), None) print 'Mailsink listening on port 25' def process_message(self, peer, mailfrom, rcpttos, data): basepath='c:\\.maildump' print 'mail from: %s to: %s' %(mailfrom, repr(rcpttos)) for rcpt in rcpttos: rcpt = rcpt.split('@')[0] try: os.mkdir(basepath+'\\'+rcpt) except OSError: pass f = file(basepath+'\\'+rcpt+'\\'+mailfrom+time.strftime('%Y%m%d%H%M%S'), 'w') f.write(data) f.close() def loop (): x = mailserver() try: asyncore.loop(timeout=2) except KeyboardInterrupt: print'interrupt' x.close() if __name__=='__main__': loop() -- http://mail.python.org/mailman/listinfo/python-list
smtp server simulation using Python
I have a (web) development computer w/o an SMTP server and want to test form generated e-mail using a dummy SMTP server that delivers the mail message to a file, or better yet, to a text editor instead of actually sending it. Is it possible to extend the DebuggingServer class,and override the process_message() method to accomplish this? If so, any suggestions are appreciated. Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: scroll a frame to display several lines of widgets at a time
Matt Hammond wrote: I don't quite understand (if I'm interpreting you correctly) why you want separate widgets, all displayed at once, for several hundred records - surely better to just reuse the one set of widgets and have the scrollbar or back-forward buttons change which record is being displayed in the widgets. I need to re-think things a little. I wanted to be able to quickly scroll through several hundred entries in the db, and check off (yes/no) which have been reviewed, updated, or whatever. I will look at having a fixed number of display widgets and scrolling through the underlying data to determine which records are currently displayed/editable. My first pass was db - display/edit widgets - db. So I jumped (incorrectly) to wanting to 'hold' all record in widgets for editing.There's no reason I can't use: db - master list - slice - display/edit widgets - master list - db. i.e. a list holding all the data, display/edit slices controlled by a scrollbar, and storing the final list when done. If you're after replacing widgets, then you need to destroy them first. Use the self.destroy method and unset/change any variables referencing the widget so it get a chance to be garbage collected. However, if you want a scrollable view onto a larger area, what you need to do is use a Canvas, with a window shape on it. You then put a frame into that window. canvas = Tkinter.Canvas( parent ) canvas.grid( ... ) winID = self.canvas.create_window(0,0, anchor=Tkinter.NW) Then later you can add a frame to that window on the canvas: canvas.itemconfigure( winID, window = my frame ) canvas['scrollregion'] = canvas.bbox('all') Make sure you've created the frame and perhaps called update_idletasks() to give it a chance to size itself before shoving it onto the canvas. And of course, the scrollbar! yscroll = Tkinter.Scrollbar( parent, orient=Tkinter.VERTICAL) yscroll.grid( ... ) yscroll['command'] = canvas.yview canvas['yscrollcommand'] = yscroll.set Probably, not needed now that I have re-thought the situation, but I do have several occasions where i need to view and select/deselect 50 or 60 options (checkbuttons). So this will make them much more manageable. Thanks, Bill On Thu, 01 Sep 2005 14:33:36 +0100, William Gill [EMAIL PROTECTED] wrote: I need to display a couple of labels and a checkbox from each entry in my database. Simple enough, but there are several hundred records, and I only want to display 5 or 10 at a time. Can this be accomplished by putting everything in a Frame(), using width, height, grid_propagate(0) , and a scrollbar? or do I have to grid 5 rows at a time? If the latter, can I just grid over the previous 5 or do they have to be explicitly removed first. Thanks. Bill -- http://mail.python.org/mailman/listinfo/python-list
scroll a frame to display several lines of widgets at a time
I need to display a couple of labels and a checkbox from each entry in my database. Simple enough, but there are several hundred records, and I only want to display 5 or 10 at a time. Can this be accomplished by putting everything in a Frame(), using width, height, grid_propagate(0) , and a scrollbar? or do I have to grid 5 rows at a time? If the latter, can I just grid over the previous 5 or do they have to be explicitly removed first. Thanks. Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: graphical or flow charting design aid for python class development?
Thanks everyone. I will explore all the suggestions, but it looks like SPE is the immediate answer. Bill William Gill wrote: Being somewhat new to Python, and having a tendency to over complicate things in my class design, I was wondering if anyone can suggest a simple graphical or flowcharting tool that they use to organize their class and program design? Because of a 55 mph head-on accident a few years back, I have short term memory problems, so flipping back and forth between pages of code is next to impossible for me to keep straight. A simple graphical model would allow me to 'see' everything in one view, and better organize my resulting code. I have had limited success using pydoc to view my classes, but it's not really much help in development, just review, and sometimes there is too much info. I have used editors for other languages that allow the view to expand and collapse functions/methods (like message threads here on the board), which help, but I haven't seen anything like this for python. Thanks for any suggestions. Bill -- http://mail.python.org/mailman/listinfo/python-list
graphical or flow charting design aid for python class development?
Being somewhat new to Python, and having a tendency to over complicate things in my class design, I was wondering if anyone can suggest a simple graphical or flowcharting tool that they use to organize their class and program design? Because of a 55 mph head-on accident a few years back, I have short term memory problems, so flipping back and forth between pages of code is next to impossible for me to keep straight. A simple graphical model would allow me to 'see' everything in one view, and better organize my resulting code. I have had limited success using pydoc to view my classes, but it's not really much help in development, just review, and sometimes there is too much info. I have used editors for other languages that allow the view to expand and collapse functions/methods (like message threads here on the board), which help, but I haven't seen anything like this for python. Thanks for any suggestions. Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: graphical or flow charting design aid for python class development?
gene tani wrote: Have you looked at class browser module? Not the graphical tool you're looking for, but maybe a good start No, it's not graphical, but it looks like I may be able to use it to put together a nice outline, or summary of my modules. It's worth exploring, thanks. Bill http://www.python.org/doc/2.0.1/lib/module-pyclbr.html William Gill wrote: Being somewhat new to Python, and having a tendency to over complicate things in my class design, I was wondering if anyone can suggest a simple graphical or flowcharting tool that they use to organize their class and program design? Because of a 55 mph head-on accident a few years back, I have short term memory problems, so flipping back and forth between pages of code is next to impossible for me to keep straight. A simple graphical model would allow me to 'see' everything in one view, and better organize my resulting code. I have had limited success using pydoc to view my classes, but it's not really much help in development, just review, and sometimes there is too much info. I have used editors for other languages that allow the view to expand and collapse functions/methods (like message threads here on the board), which help, but I haven't seen anything like this for python. Thanks for any suggestions. Bill -- http://mail.python.org/mailman/listinfo/python-list
a list of Checkbuttons
OK I'm tired, I've got a cold, and my brain isn't working very well. I have a result set ( a tuple of tuples) from a db. Each element has two elements; classification number, and classification heading. i.e. result=((001,'heading one'),(002,'heading two'),...) classification numbers may not be in numerical order, and may skip numbers, so they are not good as an index. I want to create tkinter Checkbuttons that allow me to select which apply to the record I'm editing. What comes to my sub-par mind is to create a list and assign Checkbuttons to each element. something like: classifications = [] for count, classification in enumerate(result): classifications.append( (IntVar(),classification[0]) ) Checkbutton(master, text=str(classification[0])+': '+classification[1] , variable=classifications[-1]).grid(row=count) then to collect which boxes are checked: for check in classifications: if check[0].get() == 1: print 'classification number %s selected % check[1][0] Is this the smartest way to do this? It should work, but will I be able to understand this 6 months from now? Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
prevent callback during initialization
I am creating several tkinter widgets. In my classes they each have a change() method that is a callback to various IntVar, and StringVar objects. Everything works fine, but don't really want to trigger the callback when I am initializing each widget/control variable. I can use a flag like self.initialized= true, and wrap the change() procedures in an if self.initialized: block. I get the impression using flags is not the preferred approach. Is there some other way to accomplish this without using a flag? Can I redefine my change() method in __init__(), or would that mess up the callback references already established? Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: a question about tkinter StringVars()
Eric Brunel wrote: On Wed, 24 Aug 2005 15:07:27 GMT, William Gill [EMAIL PROTECTED] wrote: Working with tkinter, I have a createWidgets() method in a class. Within createWidgets() I create several StringVars() and assign them to the textvariable option of several widgets. Effectively my code structure is: def createWidgets(self): ... var = StringVar() Entry(master,textvariable=var) ... ... Though 'var' would normally go out of scope when createWidgets completes, since the Entry and its reference do not go out of scope, only the name 'var' goes out of scope, not the StringVar object, Right? Well, apparently not: from Tkinter import * class MyStringVar(StringVar): def __del__(self): print I'm dying! root = Tk() def cw(): var = MyStringVar() Entry(root, textvariable=var).pack() cw() root.mainloop() Running this script actually prints I'm dying!, so there is obviously no reference from the Entry widget to the variable object. The reference is actually kept at tcl level between an entry and the *tcl* variable, which knows nothing about the *Python* variable. BTW, the whole purpose of StringVar's is to be kept so that the text for the entry can be retrieved or modified by another part of the program. So what can be the purpose of creating variables in a function or method and not keeping them anywhere else than a local variable? I posted that changing back to a non-local variable works now, and that my problem was probably name conflict. I haven't been able to verify that, but I have to assume that was the original problem. My band-aid may have 'worked' because tcl maintained the control variable and callback even though the Python variable was gone. As far as ... the purpose of creating variables ... and not keeping them anywhere else I actually was keeping them in a non-local list. I was creating a local variable, appending it to the list, then reusing the local name for the next new control variable: ... var= IntVar() self.variables.append(var) ... This was 'copied' from a snippet I was using as a template. I now use: ... self.variables.append(IntVar()) ... Please let me know if I'm on thin ice here. Bill -- http://mail.python.org/mailman/listinfo/python-list
a question about tkinter StringVars()
Working with tkinter, I have a createWidgets() method in a class. Within createWidgets() I create several StringVars() and assign them to the textvariable option of several widgets. Effectively my code structure is: def createWidgets(self): ... var = StringVar() Entry(master,textvariable=var) ... ... Though 'var' would normally go out of scope when createWidgets completes, since the Entry and its reference do not go out of scope, only the name 'var' goes out of scope, not the StringVar object, Right? Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: a question about tkinter StringVars()
Eric Brunel wrote: On Wed, 24 Aug 2005 15:07:27 GMT, William Gill [EMAIL PROTECTED] wrote: Working with tkinter, I have a createWidgets() method in a class. Within createWidgets() I create several StringVars() and assign them to the textvariable option of several widgets. Effectively my code structure is: def createWidgets(self): ... var = StringVar() Entry(master,textvariable=var) ... ... Though 'var' would normally go out of scope when createWidgets completes, since the Entry and its reference do not go out of scope, only the name 'var' goes out of scope, not the StringVar object, Right? Well, apparently not: from Tkinter import * class MyStringVar(StringVar): def __del__(self): print I'm dying! root = Tk() def cw(): var = MyStringVar() Entry(root, textvariable=var).pack() cw() root.mainloop() Running this script actually prints I'm dying!, so there is obviously no reference from the Entry widget to the variable object. The reference is actually kept at tcl level between an entry and the *tcl* variable, which knows nothing about the *Python* variable. I will have to do some experimenting. BTW, the whole purpose of StringVar's is to be kept so that the text for the entry can be retrieved or modified by another part of the program. So what can be the purpose of creating variables in a function or method and not keeping them anywhere else than a local variable? I was trying to keep my question simple. In actuality, I have a widget I'll call dataForm that extends tkSimpleDialog.Dialog. In it I have several entry and checkbox widgets, and a call to a changed() method passed from the parent. When I'm done editing dataForm, all the variables are processed in a save() method, and dataForm is destroyed. What happened when I used self.var = MyStringVar() and Entry(root, textvariable=self.var).pack(), is that a subsequent call to create a dataForm instance has residual data from the previous instance AND the change callback caused an error. Changing to local variables seemed to cure the problems. I just tried changing back to the self.var approach, and it seems to work fine??? I must have had some name conflicts in my earlier code. I'll try to figure it out, and post if I do. Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter text widget question
rafi wrote: William Gill wrote: The tkinter text widget uses indexes to identify row:column offsets within the text, but it seems counter intuitive to have to convert row and column integers to a string like 0.1'. It's great that index can take a string, but what about looping through rows and columns? Am I missing a way to use integers directly, or should I create a class that takes the two integers and returns them formatted as the proper string? tkinter relies on tk that is for tcl at first, and in tcl every thing is a string (more or less). %s.%s % (row, column) Simple enough. (sometimes I can't see the simplest things, without complicating them) Thanks, Bill should answer your problem easily my 2 cents -- http://mail.python.org/mailman/listinfo/python-list
tkinter text widget question
The tkinter text widget uses indexes to identify row:column offsets within the text, but it seems counter intuitive to have to convert row and column integers to a string like 0.1'. It's great that index can take a string, but what about looping through rows and columns? Am I missing a way to use integers directly, or should I create a class that takes the two integers and returns them formatted as the proper string? Thanks Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: help with mysql cursor.execute()
Dennis Lee Bieber wrote: On Sun, 14 Aug 2005 19:28:04 GMT, William Gill [EMAIL PROTECTED] declaimed the following in comp.lang.python: I have been trying to pass parameters as indicated in the api. when I use: sql= 'select * from %s where cusid = %s ' % name,recID) Cursor.execute(sql) it works fine, but when I try : sql= 'select * from %s where cusid like %s ' Cursor.execute(sql,(name,recID)) Hypothesis: the database TABLE may need to be filled in externally. .execute() parsing is designed to properly quote arguments for data fields where needed. I suspect you are getting quote marks around the table name, which is not a position they are expected. From my testing, your suspicion is correct, as is your suggestion. sql = 'select * from %s where cusid = %%s ' % tablename Cursor.execute(sql, (recID,)) works, Bill You'll likely have to use a two-step process: use string formatting to fill in table and field names (if you are getting those from user input, you'll have to validate that there isn't an injection attack -- ie, user didn't enter name; delete from name as the table to be processed); then use .execute() to pass the field values. If using MySQLdb, you could always read the source files... (Though, unfortunately, the very bottom is a compiled library and hence unreadable... You'll find .execute() invokes an .escape() Py escape(...) Py escape(obj, dict) -- escape any special characters in object obj Py using mapping dict to provide quoting functions for each type. Py Returns a SQL literal string. Note the last line: it returns a literal string -- in the form needed to pass /data/. That won't work for field and table names, and MySQLdb doesn't attempt any semantic parsing to find out is being substituted -- if just converts (escapes) ALL parameters based on datatype, THEN does a normal Python string formatting operation. -- http://mail.python.org/mailman/listinfo/python-list
Re: help with mysql cursor.execute()
Steve Holden wrote: William Gill wrote: I have been testing and it seems that: 1- Cursor.execute does not like '?' as a placeholder in sql The particular format required by each DBI-compatible module should be available as the module's paramstyle variable. mxODBC, for example, uses the qmark style, but MySQLdb uses format. 2- Cursor.execute accepts '%s' but puts the quotation mark around the substitution. sql = 'select * from %s where cusid = ? ' % name Cursor.execute(sql, (recID,)) still fails, but: sql = 'select * from basedata where cusid = %s ' Cursor.execute(sql, (recID,)) works regardless of recID being a string or an int. Obviously this stems from trying to parameterize the table name. That's correct, as Scott has pointed out (with a good explanation of why). If I use: sql = 'select * from %s where cusid = %%s ' % name Cursor.execute(sql, (recID,)) It makes 1 substitution in the first line, and another in the execute() sql = 'select * from %s where cusid = %%s ' % name # sql now == 'select * from basedata where cusid = %s ' Cursor.execute(sql, (recID,)) and it works. That's right: you are now building a table-dependent query (i.e. the table name is hard-wired in the SQL string) parameterized to the required value for cusid. Between your comments re: column names and table names , and the notes in cursor.py, I was able to figure it out. FYI I wanted to create a tableHandler class that could be extended for individual tables. That's why the query needs to accept variables for tablename. You might want to take a look at how some existing object-mappers achieve this - Ian Bicking's sqlobject module might be a good place to start. I also might want to take a tutorial on searching. This looks like it could have saved me lots of wheel re-inventing. Thanks, Bill regards Steve Thanks. Bill Scott David Daniels wrote: William Gill wrote: I have been trying to pass parameters as indicated in the api. when I use: sql= 'select * from %s where cusid = %s ' % name,recID) Cursor.execute(sql) it works fine, but when I try : sql= 'select * from %s where cusid like %s ' Cursor.execute(sql,(name,recID)) or sql= 'select * from ? where cusid like ? ' Cursor.execute(sql,(name,recID)) it fails. Can someone help me with the semantics of using parameterized queries? Neither column names nor table names can be parameters to fixed SQL. Values are what you fiddle with. This squares with the DBMS being allowed to plan the query before looking at the parameters (deciding which indices to use, which tables to join first, ...), then reusing the plan for identical queries with different values. MySQL may not take advantage of this two-step approach, but the DB interface is designed to allow it, so the parameterization is constrained. See if something like this works: sql = 'select * from %s where cusid like ? ' % name Cursor.execute(sql, (recID,)) --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
help with mysql cursor.execute()
I have been trying to pass parameters as indicated in the api. when I use: sql= 'select * from %s where cusid = %s ' % name,recID) Cursor.execute(sql) it works fine, but when I try : sql= 'select * from %s where cusid like %s ' Cursor.execute(sql,(name,recID)) or sql= 'select * from ? where cusid like ? ' Cursor.execute(sql,(name,recID)) it fails. Can someone help me with the semantics of using parameterized queries? Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: help with mysql cursor.execute()
I have been testing and it seems that: 1- Cursor.execute does not like '?' as a placeholder in sql 2- Cursor.execute accepts '%s' but puts the quotation mark around the substitution. sql = 'select * from %s where cusid = ? ' % name Cursor.execute(sql, (recID,)) still fails, but: sql = 'select * from basedata where cusid = %s ' Cursor.execute(sql, (recID,)) works regardless of recID being a string or an int. Obviously this stems from trying to parameterize the table name. If I use: sql = 'select * from %s where cusid = %%s ' % name Cursor.execute(sql, (recID,)) It makes 1 substitution in the first line, and another in the execute() sql = 'select * from %s where cusid = %%s ' % name # sql now == 'select * from basedata where cusid = %s ' Cursor.execute(sql, (recID,)) and it works. Between your comments re: column names and table names , and the notes in cursor.py, I was able to figure it out. FYI I wanted to create a tableHandler class that could be extended for individual tables. That's why the query needs to accept variables for tablename. Thanks. Bill Scott David Daniels wrote: William Gill wrote: I have been trying to pass parameters as indicated in the api. when I use: sql= 'select * from %s where cusid = %s ' % name,recID) Cursor.execute(sql) it works fine, but when I try : sql= 'select * from %s where cusid like %s ' Cursor.execute(sql,(name,recID)) or sql= 'select * from ? where cusid like ? ' Cursor.execute(sql,(name,recID)) it fails. Can someone help me with the semantics of using parameterized queries? Neither column names nor table names can be parameters to fixed SQL. Values are what you fiddle with. This squares with the DBMS being allowed to plan the query before looking at the parameters (deciding which indices to use, which tables to join first, ...), then reusing the plan for identical queries with different values. MySQL may not take advantage of this two-step approach, but the DB interface is designed to allow it, so the parameterization is constrained. See if something like this works: sql = 'select * from %s where cusid like ? ' % name Cursor.execute(sql, (recID,)) --Scott David Daniels [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
problem extending tkSimpleDialog.Dialog
I have created a widget that extends Frame() and contains labels, checkboxes, and entrys. I am trying to use tkSimpleDialog.Dialog to create a modal display of this widget, but am running into some (addressing) problems. My widget displays in the parent widget, not the tkSimpleDialog.Dialog? I hope this snippet is enough to help, as my actual code is really too hard to follow. class showtestWidget(tkSimpleDialog.Dialog): def body(self,master): Label(master,text=showPhoneNums).grid() testWidget(self).grid() class testWidget(Frame): def __init__(self, master): Frame.__init__(self) self.createWidgets() def createWidgets(self): Label(self,text=testWidget).grid() When the parent script instantiates showtestWidget() it should create a transient dialog containing a label with the text showPhoneNums. It does, but the label containing the text testWidget is being created in the parent widget, not the dialog. It seems obvious to me that I'm addressing the wrong parent somehow, since the label (probably the testWidget) is being created, but in the wrong place. I tried changing testWidget(self).grid() to testWidget(master).grid(), just to see if that helped, but it made no difference. Can someone show me where I went wrong? Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: problem extending tkSimpleDialog.Dialog
I'm still hammering away, and have found that when I change: class testWidget(Frame): def __init__(self, master): Frame.__init__(self) self.createWidgets() def createWidgets(self): Label(self,text=testWidget).grid() to: def __init__(self, master): Frame.__init__(self) self.x=master self.createWidgets() def createWidgets(self): Label(self.x,text=testWidget).grid() It seems to work correctly. However my actual widget, an extended Frame widget, still doesn't work correctly. This seems to confirm what I thought about addressing the correct parent, but I still haven't figured it out completely. Unless someone can give me a clue, I guess I can keep modifying testWidget(Frame) to add the components of my original until I can see where it breaks down. On the surface it looks like I'm not passing the correct master reference to my frame. Bill William Gill wrote: I have created a widget that extends Frame() and contains labels, checkboxes, and entrys. I am trying to use tkSimpleDialog.Dialog to create a modal display of this widget, but am running into some (addressing) problems. My widget displays in the parent widget, not the tkSimpleDialog.Dialog? I hope this snippet is enough to help, as my actual code is really too hard to follow. class showtestWidget(tkSimpleDialog.Dialog): def body(self,master): Label(master,text=showPhoneNums).grid() testWidget(self).grid() class testWidget(Frame): def __init__(self, master): Frame.__init__(self) self.createWidgets() def createWidgets(self): Label(self,text=testWidget).grid() When the parent script instantiates showtestWidget() it should create a transient dialog containing a label with the text showPhoneNums. It does, but the label containing the text testWidget is being created in the parent widget, not the dialog. It seems obvious to me that I'm addressing the wrong parent somehow, since the label (probably the testWidget) is being created, but in the wrong place. I tried changing testWidget(self).grid() to testWidget(master).grid(), just to see if that helped, but it made no difference. Can someone show me where I went wrong? Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: problem extending tkSimpleDialog.Dialog
Problem solved. I was not properly passing the master widget reference in my frame classes class MyWidget(Frame): def __init__(self, master, columns,rows, trace_write=None): Frame.__init__(self) # here's my mistake ... ... ... should have been: class MyWidget(Frame): def __init__(self, master, columns,rows, trace_write=None): Frame.__init__(self,master) ... ... ... Bill P.S. I haven't been working on this since my last post. I had to quit to go see my oldest graduate. William Gill wrote: I have created a widget that extends Frame() and contains labels, checkboxes, and entrys. I am trying to use tkSimpleDialog.Dialog to create a modal display of this widget, but am running into some (addressing) problems. My widget displays in the parent widget, not the tkSimpleDialog.Dialog? I hope this snippet is enough to help, as my actual code is really too hard to follow. class showtestWidget(tkSimpleDialog.Dialog): def body(self,master): Label(master,text=showPhoneNums).grid() testWidget(self).grid() class testWidget(Frame): def __init__(self, master): Frame.__init__(self) self.createWidgets() def createWidgets(self): Label(self,text=testWidget).grid() When the parent script instantiates showtestWidget() it should create a transient dialog containing a label with the text showPhoneNums. It does, but the label containing the text testWidget is being created in the parent widget, not the dialog. It seems obvious to me that I'm addressing the wrong parent somehow, since the label (probably the testWidget) is being created, but in the wrong place. I tried changing testWidget(self).grid() to testWidget(master).grid(), just to see if that helped, but it made no difference. Can someone show me where I went wrong? Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: cut paste text between tkinter widgets
handy. Thanks, Bill [EMAIL PROTECTED] wrote: Here's some code that gives a cut-copy-paste pop-up window on all Entry widgets in an application. This code is released into the public domain. Jeff Epler # import Tkinter def make_menu(w): global the_menu the_menu = Tkinter.Menu(w, tearoff=0) the_menu.add_command(label=Cut) the_menu.add_command(label=Copy) the_menu.add_command(label=Paste) def show_menu(e): w = e.widget the_menu.entryconfigure(Cut, command=lambda: w.event_generate(Cut)) the_menu.entryconfigure(Copy, command=lambda: w.event_generate(Copy)) the_menu.entryconfigure(Paste, command=lambda: w.event_generate(Paste)) the_menu.tk.call(tk_popup, the_menu, e.x_root, e.y_root) t = Tkinter.Tk() make_menu(t) e1 = Tkinter.Entry(); e1.pack() e2 = Tkinter.Entry(); e2.pack() e1.bind_class(Entry, Button-3ButtonRelease-3, show_menu) t.mainloop() # -- http://mail.python.org/mailman/listinfo/python-list
cut paste text between tkinter widgets
Is there a simple way to cut and paste from a tkinter text widget to an entry widget? I know I could create a mouse button event that triggers a popup (message widget) prompting for cut/paste in each of the widgets using a temp variable to hold the text, but I don't wnat to reinvent the wheel if there already is something that does the job. Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: cut paste text between tkinter widgets
Is there a simple way to cut and paste from a tkinter text widget to an entry widget? I know I could create a mouse button event that triggers a popup (message widget) prompting for cut/paste in each of the widgets using a temp variable to hold the text, but I don't wnat to reinvent the wheel if there already is something that does the job. 1) TKinter text and entry widgets should already have proper event bindings for cut/copy/paste. Test first with your system-default keyboard shortcuts (^C, ^X, ^V on Windows). I haven't tried it myself, but I think those events bind to 'Cut', 'Copy', and 'Paste', so generating them should Do The Right Thing with selected text. ^C, ^X, and ^V work just fine! (I swear I tried that before I posted and they didn't???) 2) If you need to do any processing on the clipboard data, look at widget.selection_get [so named because of the way that X handles its clipboard] From my reading, w.selection_get will return the selected text in w, and places it on the clipboard. I didn't see any way to get data from the clipboard. Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: main window in tkinter app
That does it!, thanks. Thinking about it, when I created a derived class with an __init__ method, I overrode the base class's init. It should have been intuitive that I needed to explicitly call baseclass.__init(self), it wasn't. It might have hit me if the fault was related to someting in baseclass.__init() not taking place, but the recursion loop didn't give me a clue. Any idea why failing to init the base class caused the loop? Bill Christopher Subich wrote: William Gill wrote: O.K. I tried from scratch, and the following snippet produces an infinite loop saying: File C:\Python24\lib\lib-tk\Tkinter.py, line 1647, in __getattr__ return getattr(self.tk, attr) If I comment out the __init__ method, I get the titled window, and print out self.var ('1') import os from Tkinter import * class MyApp(Tk): var=1 def __init__(self): pass def getval(self): return self.var app = MyApp() app.title(An App) print app.getval() app.mainloop() You're not calling the parent's __init__ inside your derived class. I would point out where the Python Tutorial points out that you should do this, but it's not in the obvious place (Classes: Inheritance). Python does -not- automagically call parent-class __init__s for derived classes, you must do that explicitly. Changing the definition of your class to the following works: class MyApp(Tk): var=1 def __init__(self): Tk.__init__(self) pass def getval(self): return self.var It works when you comment out __init__ because of a quirk in Python's name resolution. As you'd logically expect, if you don't define a function in a derived class but call it (such as instance.method()), it will call the method from the base class. You just proved that this works for __init__ methods also. When you didn't define __init__ for your derived class, MyApp() called Tk.__init__(), which Does the Right Thing in terms of setting up all the specific Tkinter-specific members. -- http://mail.python.org/mailman/listinfo/python-list
Re: main window in tkinter app
I never ran into this problem. ... O.K. That, means I probably have something else wrong. I will need to start with a 'clean slate' instead of trying to modify existing code. It's getting to convoluted to follow anyway after all the cobbling I've done. If I get a repeat of the original problem I will post the code and the exact error message, but at least now I know It SHOULD work. Thanks Bill, Eric Brunel wrote: On Mon, 18 Jul 2005 16:57:51 GMT, William Gill [EMAIL PROTECTED] wrote: A short while ago someone posted that(unlike the examples) you should use Tk as the base for your main window in tkinter apps, not Frame. Thus : class MyMain(Frame): def __init__(self, master): self.root = master self.master=master self.createWidgets() def createWidgets(): ... root = Tk() app = MyMain(root) app.master.title(Object Editor) root.mainloop() would become: class MyMain(Tk): ... ... app = MyMain() app.title(My App) app.mainloop() When I try converting to this approach I run into a problem with the __init__() method. It appears to go into an infinite loop in tkinter.__getattr__(). [...] I never ran into this problem. Can you please post a short script showing this behavior? Without knowing what you exactly do in your __init__ and createWidgets method, it's quite hard to figure out what happens... -- http://mail.python.org/mailman/listinfo/python-list
Re: main window in tkinter app
O.K. I tried from scratch, and the following snippet produces an infinite loop saying: File C:\Python24\lib\lib-tk\Tkinter.py, line 1647, in __getattr__ return getattr(self.tk, attr) If I comment out the __init__ method, I get the titled window, and print out self.var ('1') import os from Tkinter import * class MyApp(Tk): var=1 def __init__(self): pass def getval(self): return self.var app = MyApp() app.title(An App) print app.getval() app.mainloop() Eric Brunel wrote: On Mon, 18 Jul 2005 16:57:51 GMT, William Gill [EMAIL PROTECTED] wrote: A short while ago someone posted that(unlike the examples) you should use Tk as the base for your main window in tkinter apps, not Frame. Thus : class MyMain(Frame): def __init__(self, master): self.root = master self.master=master self.createWidgets() def createWidgets(): ... root = Tk() app = MyMain(root) app.master.title(Object Editor) root.mainloop() would become: class MyMain(Tk): ... ... app = MyMain() app.title(My App) app.mainloop() When I try converting to this approach I run into a problem with the __init__() method. It appears to go into an infinite loop in tkinter.__getattr__(). [...] I never ran into this problem. Can you please post a short script showing this behavior? Without knowing what you exactly do in your __init__ and createWidgets method, it's quite hard to figure out what happens... -- http://mail.python.org/mailman/listinfo/python-list
Re: main window in tkinter app
It also seems to operate the same with or without app.mainloop(). Is an explicit call to mainloop needed? William Gill wrote: O.K. I tried from scratch, and the following snippet produces an infinite loop saying: File C:\Python24\lib\lib-tk\Tkinter.py, line 1647, in __getattr__ return getattr(self.tk, attr) If I comment out the __init__ method, I get the titled window, and print out self.var ('1') import os from Tkinter import * class MyApp(Tk): var=1 def __init__(self): pass def getval(self): return self.var app = MyApp() app.title(An App) print app.getval() app.mainloop() Eric Brunel wrote: On Mon, 18 Jul 2005 16:57:51 GMT, William Gill [EMAIL PROTECTED] wrote: A short while ago someone posted that(unlike the examples) you should use Tk as the base for your main window in tkinter apps, not Frame. Thus : class MyMain(Frame): def __init__(self, master): self.root = master self.master=master self.createWidgets() def createWidgets(): ... root = Tk() app = MyMain(root) app.master.title(Object Editor) root.mainloop() would become: class MyMain(Tk): ... ... app = MyMain() app.title(My App) app.mainloop() When I try converting to this approach I run into a problem with the __init__() method. It appears to go into an infinite loop in tkinter.__getattr__(). [...] I never ran into this problem. Can you please post a short script showing this behavior? Without knowing what you exactly do in your __init__ and createWidgets method, it's quite hard to figure out what happens... -- http://mail.python.org/mailman/listinfo/python-list
main window in tkinter app
A short while ago someone posted that(unlike the examples) you should use Tk as the base for your main window in tkinter apps, not Frame. Thus : class MyMain(Frame): def __init__(self, master): self.root = master self.master=master self.createWidgets() def createWidgets(): ... root = Tk() app = MyMain(root) app.master.title(Object Editor) root.mainloop() would become: class MyMain(Tk): ... ... app = MyMain() app.title(My App) app.mainloop() When I try converting to this approach I run into a problem with the __init__() method. It appears to go into an infinite loop in tkinter.__getattr__(). If I omit __init__() I get a properly titled window, but must explicitly call my createWidgets method from __main__. class MyMain(Tk): createWidgets() ... ... app = MyMain() app.title(My App) app.createWidgets() app.mainloop() Am I missing something? Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: Tkinter grid layout
Excuse me for intruding, but I followed examples and ended up with a similar architecture: from Tkinter import * class MyMain(Frame): def __init__(self, master): self.root = master self.master=master root = Tk() app = MyMain(root) app.master.title(Object Editor) root.mainloop() Erick, are you saying it should be modified to something like : from Tkinter import * class MyMain(Tk): ... ... app = MyMain() app.title(My App) app.mainloop() Thanks, Bill Eric Brunel wrote: On Wed, 06 Jul 2005 11:44:55 +0100, Richard Lewis [EMAIL PROTECTED] wrote: Hi there, I've got a tree control in Tkinter (using the ESRF Tree module) but I can't get it to layout how I want it. I'd like to have it so that it streches north/south (anchored to the top and bottom), is of a fixed width and is anchored to the left hand side. Here's my code (its derived from one of the examples from the ESRF web site): class MainWindow(Frame): [snip code] First of all, it is not a good idea to make your so-called window inherit from Frame: a Frame is not a window in tk, but a generic container. Creating a Frame without a container window will automatically initialize the tk toolkit, creating a default window which will become the default parent for widgets where you don't specify one. According to the well-known explicit is better than implicit principle, if a MainWindow instance are actually the main window for your application, you'd really better inherit from the Tkinter class for the main window, which is Tk. Doing it this way has a lot of advantages over what you do; for example, if you later have to create a menu bar for your application, you will be able to do it in the MainWindow class. If you inherit from Frame, you won't get any access to the actual window, so you won't be able to create a menu in it. This may seems to be unrelated to your problem, but it's not: by creating a Frame, you introduce one more unneeded container. So, in some code you don't show here, you have to insert the MainWindow instance into its parent window via a call to its pack or grid method. Since the code you show seems to be correct, I guess the problem is in this call to pack or grid, which probably does not tell the Frame how to behave when its parent window is resized, causing it to get the default behaviour, which is do nothing at all. To be sure this actually is the problem, try to replace the line: Frame.__init__(self, master) in MainWindow.__init__ by: Frame.__init__(self, master, bg='blue', bd=2) This way, a blue border will appear around the frame, allowing you to see how it grows. Then run your application, and resize the window. You should see that the frame does not grow when the window grows, explaining why your tree deos not grow (in fact, it would grow if its container did; but its container doesn't...) So you should either make your MainWindow class inherit from Tk, which eliminates the unneeded container and the problems it may cause, or make sure the pack or grid on your MainWindow instance actually tells the container to grow with its container. With pack, it's quite easy: just do myWindow.pack(fill=BOTH, expand=1). With grid, it's a bit more complicated, since you will have to configure the grid on the container. But basically, my advice would be: - Never make your windows inherit from Frame; make them inherit from Tk for the main window or from Toplevel for all other ones - When you have resize problems, always check the whole widget hierarchy from the actual window down to the widget showing the problem. The cause is very often not on the widget itself, but on one of its containers. HTH -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter radiobutton
I did some more digging based on your code, and discovered list comprehensions. They didn't register the first time I skimmed the language reference and tutorial. It's obvious the more I learn, the more I need to relearn what I think I know. I need to study comprehensions, but they open up lots of opportunities for simpler, clearer code. return row == var.get() Oops! I saw this as soon as I sent it, but knew you would get my point. var.set(-1) Though both ways may seem roughly equivalent today, I'd bet that in 6 months ... var.set(-1) # initialize as no choice ... will be clearer. Thanks again! Bill Peter Otten wrote: William Gill wrote: Also, does 'row == var.get() for var in self.variables' perform the comparison row == var.get() for each item in self.variables? I would have had to write: for var in self.variables: return row == var.get() Or rather result = [] for var in self.variables: result.append(row == var.get()) return tuple(result) This can be rewritten to a 'list comprehension' return tuple([row == var.get() for var in self.variables]) and, since Python 2.4, to the 'generator expression' that I used and which avoids building the intermediate list. Both constructs also feature an if-clause, see http://docs.python.org/tut/node7.html#SECTION00714 http://docs.python.org/tut/node11.html#SECTION000 p.s. I tweaked rbn = tk.Radiobutton(self, text=text, variable=var, value=y) to rbn = tk.Radiobutton(self, text=text, variable=var, value=y+1) and return tuple(row == var.get() for var in self.variables) to return tuple(row+1 == var.get() for var in self.variables) so that the Radiogrid doesn't initialize w/row 1 selected, and accomodates cases where nothing is selected in any column. Another option would have been to initialize the variables ... var = tk.IntVar() var.set(-1) if trace_write: ... Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter radiobutton
or use a custom subclass ... I had considered extending radiobutton to add whatever properties needed, but the net/net is the same, that property must be set using methods that trigger on the rb command procedure, or an external (to the rb) control variable value. The radiobutton widget knows if it is selected or unselected, or it wouldn't be able to display correctly, but based on what I'm seeing, that information is inaccessable to the app. Instead the app must evaluate an associated control variable. That doesn't make sence to me, but even trying to look at the code for the radiobutton class didn't help. I guess I need to set up an observer on the control variable, or a command procedure on the radiobutton (effectively to create my own control variable). I know I can 'slice' my original 4 X 4 matrix vertically, by associating a different intVar to each 'column', but I can't figure out how to 'slice' them horizontally w/o breaking their vertical relationships. Bill Peter Otten wrote: William Gill wrote: I am placing radiobuttons in a 4 X 4 matrix (using loops) and keep references to them in a 2 dimensional list ( rBtns[r][c] ). It works fine, and I can even make it so only one button per column can be selected, by assigning each column to an intVar. In many languages a radiobutton has a property that can be directly read to see if it is selected on unselected. Tkinter radiobuttons don't seem to have any such property. Is there any way to look (via the script not the screen) to determine if it is selected?, or can this only be achieved via control variables? You can either write a little helper function def selected(rbn): return rbn.getvar(rbn[variable]) == rbn[value] or use a custom subclass of Tkinter.Radiobutton with a 'selected' attribute: class Radiobutton(Tkinter.Radiobutton): def __getattr__(self, name): if name == selected: return self.getvar(self[variable]) == self[value] raise AttributeError Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter radiobutton
I thought the problem was practical, not philosophical, but what do I know I'm the one asking for help. I have radiobuttons arranged in 4 rows of 4 buttons each ( 4 rows and 4 columns ) The user can select no more than 1 choice in any column, but any number in any row. Restated: columns can have 0 or 1 selection rows can have 0,1,2,3, or 4 selections. Columns can be restricted to 0 or 1 selection through the use of an intVar. So we now have 4 intVars (control variables) The app needs to examine the buttons and aggregate the selections for each row, efectively converting columnar information to row information. one solution: Create 4 intVars Column0 = intVar() Column1 = intVar() Column2 = intVar() Column3 = intVar() Assign 0, 1, 2, 3 and 4 to values to correspond to the row number. Row1rb1 = Radiobutton(self, variable = Column0, value = 1) Row1rb2 = Radiobutton(self, variable = Column1, value = 1) Row1rb3 = Radiobutton(self, variable = Column2, value = 1) Row1rb4 = Radiobutton(self, variable = Column3, value = 1) Row2rb1 = Radiobutton(self, variable = Column0, value = 2) Row2rb2 = Radiobutton(self, variable = Column1, value = 2) … … Row4rb4 = Radiobutton(self, variable = Column3, value = 4) to 'read' the user's response: Loop through the 4 intVars 4 times; compare their value to the value for the row being processed; if they are the same bitor a value to a rowVariable i.e. convert the column information (intVar values) to row information. Bill Peter Otten wrote: William Gill wrote: The radiobutton widget knows if it is selected or unselected, or it wouldn't be able to display correctly, but based on what I'm seeing, that information is inaccessable to the app. Instead the app must evaluate an associated control variable. That doesn't make sence to me, but even trying to look at the code for the radiobutton class didn't help. I guessed you wanted to solve a practical problem, but the thoughts expressed above suggest, err, philosophical qualms. So, for the sake of the argument and since we both don't know the implementation details, be it in C or TCL, let's assume that the individual radiobuttons do *not* /know/ whether they are selected or not but instead compare their associated 'variable' with their 'value' every time they are /asked/ to draw themselves. That would avoid duplicate state and require only log N instead of N bits. Wouldn't that be an elegant implementation, at least in theory? So why bother about the layers below when you have all the information to write code that works? Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter radiobutton
What follows looks more like a spec than a question. It is, but I wanted to show why I was getting confused trying to use control variables to maintain the overall relationship. Thank you. This is exactly what I'm trying to do, and oddly enough similar in concept to what I was doing, but far more readable and maintainable (thus the philosophical component :-)) using 'for x, column in enumerate(columns):' for a looping structure cleared up a lot of the convoluted 'score keeping' I was trying to do in my nested loops. Also, does 'row == var.get() for var in self.variables' perform the comparison row == var.get() for each item in self.variables? I would have had to write: for var in self.variables: return row == var.get() Again, thanks. Bill Peter Otten wrote: William Gill wrote: I thought the problem was practical, not philosophical, but what do I know I'm the one asking for help. What follows looks more like a spec than a question. columns can have 0 or 1 selection rows can have 0,1,2,3, or 4 selections. Loop through the 4 intVars 4 times; compare their value to the value for the row being processed; if they are the same bitor a value to a rowVariable i.e. convert the column information (intVar values) to row information. Here's my implementation: import Tkinter as tk class Radiogrid(tk.Frame): def __init__(self, master, columns, trace_write=None): tk.Frame.__init__(self) self.variables = [] self.buttons = [] for x, column in enumerate(columns): var = tk.IntVar() if trace_write: var.trace_variable(w, trace_write) self.variables.append(var) self.buttons.append([]) for y, text in enumerate(column): rbn = tk.Radiobutton(self, text=text, variable=var, value=y) rbn.grid(column=x, row=y) self.buttons[-1].append(rbn) def get_row_state(self, row): return tuple(row == var.get() for var in self.variables) if __name__ == __main__: root = tk.Tk() def show_state(*args): for i in range(3): print row, i, rg.get_row_state(i) print rg = Radiogrid(root, [alpha beta gamma.split(), one two three.split(), guido van rossum.split()], show_state ) rg.pack() root.mainloop() I hope this will move further discussion from the abstract to the concrete :-) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter radiobutton
p.s. I tweaked rbn = tk.Radiobutton(self, text=text, variable=var, value=y) to rbn = tk.Radiobutton(self, text=text, variable=var, value=y+1) and return tuple(row == var.get() for var in self.variables) to return tuple(row+1 == var.get() for var in self.variables) so that the Radiogrid doesn't initialize w/row 1 selected, and accomodates cases where nothing is selected in any column. Bill Peter Otten wrote: William Gill wrote: I thought the problem was practical, not philosophical, but what do I know I'm the one asking for help. What follows looks more like a spec than a question. columns can have 0 or 1 selection rows can have 0,1,2,3, or 4 selections. Loop through the 4 intVars 4 times; compare their value to the value for the row being processed; if they are the same bitor a value to a rowVariable i.e. convert the column information (intVar values) to row information. Here's my implementation: import Tkinter as tk class Radiogrid(tk.Frame): def __init__(self, master, columns, trace_write=None): tk.Frame.__init__(self) self.variables = [] self.buttons = [] for x, column in enumerate(columns): var = tk.IntVar() if trace_write: var.trace_variable(w, trace_write) self.variables.append(var) self.buttons.append([]) for y, text in enumerate(column): rbn = tk.Radiobutton(self, text=text, variable=var, value=y) rbn.grid(column=x, row=y) self.buttons[-1].append(rbn) def get_row_state(self, row): return tuple(row == var.get() for var in self.variables) if __name__ == __main__: root = tk.Tk() def show_state(*args): for i in range(3): print row, i, rg.get_row_state(i) print rg = Radiogrid(root, [alpha beta gamma.split(), one two three.split(), guido van rossum.split()], show_state ) rg.pack() root.mainloop() I hope this will move further discussion from the abstract to the concrete :-) Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: tkinter radiobutton
to determine if it is selected?, or can this only be achieved via control variables? The value and variable options for a radiobutton seem to be what you're looking for. Thanks, I knew that, but I was looking for a way to read the selected/unselected status directly. Using control variables gets a little messy because of the relationship of the rb matrix. They are arranged in a 4 X 4 matrix where each column is grouped (via intVars) so that no more than 1 rb per column can be selected, but each row makes up the 'status' on one 'item' so any combination of buttons in a row is acceptable. One solution I have been contemplating requires setting the value of each rb to the row number ( 0, 1, 2, or 3 or 1,2,3, or 4 in case I need to use 0 for 'none selected'), and using one intVar for each column. Then I would have to loop through all four intVars four times to determine which radiobuttons are selected in each row. That's what I mean by messy. Bill Eric Brunel wrote: On Sat, 25 Jun 2005 19:34:50 GMT, William Gill [EMAIL PROTECTED] wrote: I am placing radiobuttons in a 4 X 4 matrix (using loops) and keep references to them in a 2 dimensional list ( rBtns[r][c] ). It works fine, and I can even make it so only one button per column can be selected, by assigning each column to an intVar. In many languages a radiobutton has a property that can be directly read to see if it is selected on unselected. Tkinter radiobuttons don't seem to have any such property. Is there any way to look (via the script not the screen) to determine if it is selected?, or can this only be achieved via control variables? The value and variable options for a radiobutton seem to be what you're looking for. Here is an example showing how to use them: from Tkinter import * root = Tk() v = StringVar() Radiobutton(root, text='foo', value='foo', variable=v).pack() Radiobutton(root, text='bar', value='bar', variable=v).pack() def p(): print v.get() Button(root, command=p, text='Print').pack() root.mainloop() HTH -- http://mail.python.org/mailman/listinfo/python-list
pass an event up to parent widget
I have a Tkinter (frame) widget that contains several other frame widgets, each containing entry widgets. In the parent frame I have a 'save' button that is initially disabled. As it is now, each widget has a hasChanged property that I can poll to see if updates to the source data need to be made. hasChanged is set to True by an event routine in each frame widget, and this works fine for my exit routine which knows to poll each widget for hasChanged. What I don't know how to do is send an event up the chain to the top so it can change the 'save' button to NORMAL (telling the user 'The data has been changed and can be saved if wanted') . I don’t think bind_class() to all entry widgets is the way to go. I could create an after() alarm callback to poll hasChanged, but again this seems to awkward. I have looked at widget.event_add() but, don't know if this is viable. I am thinking a virtual event without any SEQUENCE, and then triggering it programmatically (from within the sub-widget event handlers). Is that doable? Isn't there a better way? Any suggestions? Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: a comprehensive Tkinter document?
Kent Johnson wrote: William Gill wrote: I know a major problem I am having is that I am finding lots of Tkinter information in 'fragments' of various , sometimes conflicting vintages. For example the python reference I was using didn't show the '%%' as an escape sequence, I posted asking how to escape the '%' and after several helpful responses voila I found a more complete table of escape sequences. Is there a comprehensive document or book that I can get that is relatively current? Maybe not comprehensive but I think reasonably current: http://www.pythonware.com/library/tkinter/introduction/index.htm http://infohost.nmt.edu/tcc/help/pubs/tkinter/ Kent Yes, these are two of my staples, though I have occasionally slipped into 'copies' elsewhere that aren't kept up. Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: access properties of parent widget in Tkinter
Kent Johnson wrote: William Gill wrote: I am trying to get set the properties of a widget's parent widget. What I have works, but seems like a long way around the block. First I get the widget name using w.winfo_parent(), then i convert the name to a reference using nametowidget(). self.nametowidget(event.widget.winfo_parent()).hasChanged= True Personally I think it is bad design for a widget to assume anything about its enclosing environment. What about passing a StringVar or IntVar to the child widget and letting it work with that? Kent Maybe I should clarify what I am doing and why, so that I can get a better understanding of your replies. The overall app is a gui editor for a database made up of several related tables; one for basic info, one for their various phone numbers (publish, contact, fax,cell, etc), one for various addresses (publish ,ship to, mail to, etc.), one for the services they subscribe to, etc. The editor brings records from each of the various tables together in one record for editing. Each table has an associated python/tkinter class (widget) that displays the fields in a parent widget, and each field is a child of the table widget. So city is a child of address, is a child of client. If I change or add a phone number that db table will need updating when Im done, but the address table may not. I have designed each table class with a hasChanged attribute, initialized to False, if a child Entry widget changes I set has changed to True. When Im done the exit routine runs each table objects save routine, which checks hasChanged to see if an update query needs to be run on that table. Client - basicData object (data from client table) - company - contact person - notes - phones object (data from phonenumber table) - type (cell, fax, publish, etc) - areaCode - exchange - base If I change the area code in one record only the phonenumber table needs to be updated, but since areaCode is a child of phones, phones.hasChanged needs to be set to True by the areaCode entry widget. Personally I think it is bad design for a widget to assume anything about its enclosing environment. What about passing a StringVar or IntVar to the child widget and letting it work with that? This is not a criticism, but how is passing a known intVar or stringVar any different than designing with the knowledge that an areaCode widget can not exist except as a child of phonenumber? Besides, I need to pass the state of areaCode (has it changed or not), not its value? Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: access properties of parent widget in Tkinter
Kent Johnson wrote: William Gill wrote: I am trying to get set the properties of a widget's parent widget. What I have works, but seems like a long way around the block. First I get the widget name using w.winfo_parent(), then i convert the name to a reference using nametowidget(). self.nametowidget(event.widget.winfo_parent()).hasChanged= True Personally I think it is bad design for a widget to assume anything about its enclosing environment. What about passing a StringVar or IntVar to the child widget and letting it work with that? Kent A little more research into stringVar, and the stringVar.trace() method may be one way to go. It may be simpler, or more convoluted having so many stringVar objects. I'll do some experimenting, but I'm still open to other ideas. Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: access properties of parent widget in Tkinter
Kent Johnson wrote: William Gill wrote: I am trying to get set the properties of a widget's parent widget. What I have works, but seems like a long way around the block. First I get the widget name using w.winfo_parent(), then i convert the name to a reference using nametowidget(). self.nametowidget(event.widget.winfo_parent()).hasChanged= True Personally I think it is bad design for a widget to assume anything about its enclosing environment. What about passing a StringVar or IntVar to the child widget and letting it work with that? Kent I stumbled across the widget.master attribute. so self.nametowidget(event.widget.winfo_parent()).hasChanged = True can be re-written as self.master.hasChanged = True I thought I was doing things the indirect way. Thanks everyone for your help. I'm still interested in if anyone thinks this is bad practice, and why. Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: access properties of parent widget in Tkinter
Kent Johnson wrote: William Gill wrote: Kent Johnson wrote: If I change the area code in one record only the phonenumber table needs to be updated, but since areaCode is a child of phones, phones.hasChanged needs to be set to True by the areaCode entry widget. One possibility is for the phones.hasChanged to poll the hasChanged attributes of its children. In other words, instead of propagating hasChanged up when a change occurs, poll the dependent widgets when you need to know. Another way would be to pass a calllback to the child widget that it calls when it is changed, or to set up some kind of event mechanism. In Java I often set the parent to monitor property change events of the child. Personally I think it is bad design for a widget to assume anything about its enclosing environment. What about passing a StringVar or IntVar to the child widget and letting it work with that? This is not a criticism, but how is passing a known intVar or stringVar any different than designing with the knowledge that an areaCode widget can not exist except as a child of phonenumber? When you pass a stringVar to the child, it knows only what it is told, it is not assuming that some incantation on its parent will do the right thing. This has a direct effect on reusability of the child in other contexts. You may think you don't want to reuse the child, but it is very handy to be able to make a small test harness for a widget rather than firing up the whole application, navigating to the correct screen, etc. It is much harder to do this if the widget depends on its enclosing environment. And I find that if I design widgets for reuse, other uses tend to come up often enough to make it worth-while. It's not that different from relying on any other global state. It makes code harder to understand, harder to test and harder to reuse. More generally, IMO it is good practice to try to make acyclic dependency graphs between classes and modules, so if the parent depends on the child, the child shouldn't depend on the parent. Besides, I need to pass the state of areaCode (has it changed or not), not its value? OK, I misunderstood your original post on that point. Kent I will digest this some more, and see if the polling of child attributes gets harder to follow than setting parent attributes. In theory it makes sense to have the independence you discuss, in this case it's hard to imaging needing the areaCode widget without the (parent) phonenumber widget, but this is the exception. So your suggestion makes more general sense. By the way, my suspicion was right, self.master.hasChanged = True , provides direct access, but now I'm not sure that's the way to go. Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
access properties of parent widget in Tkinter
I am trying to get set the properties of a widget's parent widget. What I have works, but seems like a long way around the block. First I get the widget name using w.winfo_parent(), then i convert the name to a reference using nametowidget(). self.nametowidget(event.widget.winfo_parent()).hasChanged= True It works, but I can't help but think I'm missing a more direct route. Am I? Bill -- http://mail.python.org/mailman/listinfo/python-list
string formatting using the % operator
I am using the % operator to create queries for a db app. It works fine when exact strings, or numbers are used, but some queries need partial matching that use the '%' as a wildcards. So for example the resultant string should be 'WHERE name LIKE %smith%' (would match silversmith, smithy, and smith). Is there any way to get something like searchterm = 'smith' sql += 'WHERE name LIKE %s' % searchterm to return 'WHERE name LIKE %smith%'I have tried using escapes, character codes for the % sign, and lots of other gyrations with no success. The only thing that works is if I modify searchterm first: searchterm = 'smith' searchterm ='%'+'smith'+'%' sql += 'WHERE name LIKE %s' % searchterm Any Ideas? Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: string formatting using the % operator
Dan Sommers wrote: On Mon, 13 Jun 2005 15:12:54 GMT, William Gill [EMAIL PROTECTED] wrote: I am using the % operator to create queries for a db app. It works fine when exact strings, or numbers are used, but some queries need partial matching that use the '%' as a wildcards. So for example the resultant string should be 'WHERE name LIKE %smith%' (would match silversmith, smithy, and smith). Is there any way to get something like searchterm = 'smith' sql += 'WHERE name LIKE %s' % searchterm to return 'WHERE name LIKE %smith%'I have tried using escapes, character codes for the % sign, and lots of other gyrations with no success. The only thing that works is if I modify searchterm first: searchterm = 'smith' searchterm ='%'+'smith'+'%' sql += 'WHERE name LIKE %s' % searchterm Any Ideas? Let the DB-API do more work for you: cursor = connection.cursor( ) sql = SELECT column2, columns3 FROM table WHERE name LIKE %s values = ('%%%s%%' % searchterm,) # note that this is a tuple cursor.execute( sql, values ) HTH, Dan I can't tell you how many times I looked at the table of format codes and missed this. Thanks everyone! -- http://mail.python.org/mailman/listinfo/python-list
Capture close window button in Tkinter
I am trying to make a simple data editor in Tkinter where each data element has a corresponding Entry widget. I have tried to use the FocusIn/FocusOut events to set a 'hasChanged' flag (if a record has not changed, the db doesnt need updating). This seems to work fine except that when the user finishes and clicks a done button or the close window button (in the root widget) no FocusOut event is triggered. I can trigger a FocusOut event if the done button opens another window (i.e. a messagebox) that takes focus. Enter and Leave follow the mouse, but dont trigger when the user tabs between fields. Is there a better way to monitor 'hasChanged'? Also, how do I capture the root window close button? Thanks, Bill -- http://mail.python.org/mailman/listinfo/python-list
Re: Capture close window button in Tkinter
Jonathan Ellis wrote: William Gill wrote: I am trying to make a simple data editor in Tkinter where each data element has a corresponding Entry widget. I have tried to use the FocusIn/FocusOut events to set a 'hasChanged' flag (if a record has not changed, the db doesn't need updating). This seems to work fine except that when the user finishes and clicks a 'done' button or the close window button (in the root widget) no FocusOut event is triggered. I can trigger a FocusOut event if the 'done' button opens another window (i.e. a messagebox) that takes focus. Enter and Leave follow the mouse, but don't trigger when the user tabs between fields. Is there a better way to monitor 'hasChanged'? I'd go with monitoring keypresses in the Entry widget. Well, It doesn't seem logical to do a before and after test of the Entry values after each keypress, but I suppose I could monitor keypresses, test event.key for Tab (in case the user tabbed out of the widget w/o making any changes. Is that along the lines of what you are suggesting? Also, how do I capture the root window close button? root = Tk() root.protocol(WM_DELETE_WINDOW, onexit) I had seen something like this somewhere, but couldn't remember where. Thanks to your reminder I found an example of Capturing destroy events. Since that will allow me to route the exit process through a tkMessageBox, it may be just as good to continue using FocusIn/FocusOut events. -- http://mail.python.org/mailman/listinfo/python-list