[Tutor] tkinter window not showing max, min and close buttons
I am working my way through Alan Gauld's tutorial and have just started the section on GUI. The windows that are created look odd with no title bar or maximise, minimise or close window button. system Python 2.7 (32 bit) Ubuntu Linux (unity) How might I get things to look like in the tutorial? Thank you Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter window not showing max, min and close buttons
On 21/07/15 17:02, Alan Gauld wrote: On 21/07/15 06:05, Chris Roy-Smith wrote: I am working my way through Alan Gauld's tutorial and have just started the section on GUI. The windows that are created look odd with no title bar or maximise, minimise or close window button. The simplest program that should show the icons is: >>> import Tkinter >>> top = Tkinter.Tk() >>> top.mainloop() What do you see when you type just those lines at the >>> prompt? All I get is a white square, with no way to close without using kill I have done a bit of tinkering and have found that it is only my user account that behaves this way. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter window not showing max, min and close buttons
On 21/07/15 21:52, Alan Gauld wrote: On 21/07/15 08:15, Chris Roy-Smith wrote: On 21/07/15 17:02, Alan Gauld wrote: On 21/07/15 06:05, Chris Roy-Smith wrote: I am working my way through Alan Gauld's tutorial and have just started the section on GUI. The windows that are created look odd with no title bar or maximise, minimise or close window button. The simplest program that should show the icons is: >>> import Tkinter >>> top = Tkinter.Tk() >>> top.mainloop() What do you see when you type just those lines at the >>> prompt? All I get is a white square, with no way to close without using kill I have done a bit of tinkering and have found that it is only my user account that behaves this way. OK, No idea why that would be happening but it may be a Unity setting - I use Mint/Cinnamon because I hated Unity... Can you try logging out and back in using a different desktop - say XFCE and see if that changes anything. That will hopefully narrow it down to a Unity v User settings issue. In either case it will probably be an issue for another forum since its unlikely to be a Python issue, but please keep me in the loop since it might affect other tutorial users. Thanks Alan, other desktops allow correct operation. Only Unity 3D has the fault, Unity-2D works fine. I had not considered that the desktop could be the problem. I hope to find the offending file or setting in the Unity configuration, as I would prefer to know how to fix this if I need to in the future. A clean install and restore isn't an option because my backup also has the offending error :( I have narrowed it down to 1 machine, so a little detective work should identify the offending file. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter window not showing max, min and close buttons
On 22/07/15 08:07, Chris Roy-Smith wrote: On 21/07/15 21:52, Alan Gauld wrote: On 21/07/15 08:15, Chris Roy-Smith wrote: On 21/07/15 17:02, Alan Gauld wrote: On 21/07/15 06:05, Chris Roy-Smith wrote: I am working my way through Alan Gauld's tutorial and have just started the section on GUI. The windows that are created look odd with no title bar or maximise, minimise or close window button. The simplest program that should show the icons is: >>> import Tkinter >>> top = Tkinter.Tk() >>> top.mainloop() What do you see when you type just those lines at the >>> prompt? All I get is a white square, with no way to close without using kill I have done a bit of tinkering and have found that it is only my user account that behaves this way. OK, No idea why that would be happening but it may be a Unity setting - I use Mint/Cinnamon because I hated Unity... Can you try logging out and back in using a different desktop - say XFCE and see if that changes anything. That will hopefully narrow it down to a Unity v User settings issue. In either case it will probably be an issue for another forum since its unlikely to be a Python issue, but please keep me in the loop since it might affect other tutorial users. Thanks Alan, other desktops allow correct operation. Only Unity 3D has the fault, Unity-2D works fine. I had not considered that the desktop could be the problem. I hope to find the offending file or setting in the Unity configuration, as I would prefer to know how to fix this if I need to in the future. A clean install and restore isn't an option because my backup also has the offending error :( I have narrowed it down to 1 machine, so a little detective work should identify the offending file. Problem solved. Unity settings are stored using GConf. Resetting Unity with the following: dconf reset -f /org/compiz/ then log out and back in. This fixed a few other mysteries at the same time (some windows could not be moved) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Abs
On 27/07/15 11:06, Job wrote: I want to be able to ask a user to input an integer and print out the root and power of the given integer. Why do you use abs(x) for this program? I don't understand or see the link between abs() and root and powers. This reminds me of this: By knowing that when x%2==1 x is an odd number and when x%2 ==0 x is even, I was able to create a program that asked the user to enter 10 integers and printed out the largest odd number . So If I understand how and why abs() is used to find the cube root of a perfect cube or how to use abs() to make the computer print out the root and power of a given integer I may make this program. Thank you and forgive for my fuzzy thoughts. Job ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor You will fine that any attempt to find the root of a negative value will result in an error. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] filtering listed directories
Hi, environment: Python 2.7, Ubuntu 12.4 Linux I am trying to get the list of directories shown by tkFileDialog.askdirectory to not show hidden files (starting with .) this code results in lots of hidden directories listed in the interface making things harder than they need to be for the user. #! /usr/bin/python import Tkinter, tkFileDialog root = Tkinter.Tk() root.withdraw() dirname = tkFileDialog.askdirectory(parent=root,initialdir="/home/chris/",title='Pick a directory') How can I filter out these hidden directories? Help(tkFileDialog) doesn't help me as it just shows **options, but doesn't show what these options might be. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filtering listed directories
On 22/08/15 23:32, Alan Gauld wrote: On 22/08/15 11:43, Laura Creighton wrote: How can I filter out these hidden directories? Help(tkFileDialog) doesn't help me as it just shows **options, but doesn't show what these options might be. tix (tkinter extensions) https://wiki.python.org/moin/Tix have some more file dialogs, so maybe there is joy there. There is a FileSelectDialog in Tix that has a dircmd option according to the Tix documentation. However, I've played about with it and can't figure out how to make it work! There is also allegedly a 'hidden' check-box subwidget that controls whether hidden files are shown. Again I couldn't find how to access this. But maybe some questions on a Tix (or Tk) forum might get more help? Once you know how to do it in native Tcl/Tk/Tix you can usually figure out how to do it in Python. Thanks for the Tcl tk hint, so I searched for info for tcl tk. Unfortunately the options appear to be the same as offered by tkinter. I had hoped that the cause of my problem would be that I'm still to learn that bit ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filtering listed directories
On 23/08/15 00:42, Laura Creighton wrote: In a message of Sat, 22 Aug 2015 14:32:56 +0100, Alan Gauld writes: But maybe some questions on a Tix (or Tk) forum might get more help? Once you know how to do it in native Tcl/Tk/Tix you can usually figure out how to do it in Python. -- Alan G I asked the question on tkinter-discuss, but the question hasn't shown up yet. In the meantime, I have found this: http://www.ccs.neu.edu/research/demeter/course/projects/demdraw/www/tickle/u3/tk3_dialogs.html which looks like, if we converted it to tkinter, would do the job, since all it wants is a list of files. I have guests coming over for dinner, so it will be much later before I can work on this. (And I will be slow -- so if you are a wizard at converting tk to tkinter, by all means feel free to step in here. :) ) Laura ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Thanks Laura, unfortunately I know next to nothing of tk, so I'll have wait. No worries, This in not an urgent thing, and is mostly a learning exercise, as I have a cli tool to do what what I'm aiming to write using Tkinter. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] filtering listed directories
On 23/08/15 18:13, Laura Creighton wrote: In a message of Sun, 23 Aug 2015 13:09:41 +1000, Chris Roy-Smith writes: On 22/08/15 23:32, Alan Gauld wrote: On 22/08/15 11:43, Laura Creighton wrote: How can I filter out these hidden directories? Help(tkFileDialog) doesn't help me as it just shows **options, but doesn't show what these options might be. tix (tkinter extensions) https://wiki.python.org/moin/Tix have some more file dialogs, so maybe there is joy there. There is a FileSelectDialog in Tix that has a dircmd option according to the Tix documentation. However, I've played about with it and can't figure out how to make it work! There is also allegedly a 'hidden' check-box subwidget that controls whether hidden files are shown. Again I couldn't find how to access this. But maybe some questions on a Tix (or Tk) forum might get more help? Once you know how to do it in native Tcl/Tk/Tix you can usually figure out how to do it in Python. Thanks for the Tcl tk hint, so I searched for info for tcl tk. Unfortunately the options appear to be the same as offered by tkinter. I had hoped that the cause of my problem would be that I'm still to learn that bit ;) No, the problem is that the tk widget is badly designed. Not only is there only minimal pattern support matching, but there is no way to subclass the thing and feed it your own list of file and directory names. It really is a case of "Do not open. No user-servicable parts to be found within." which is frustrating. Laura Thanks Laura, I don't use idle but wondered how it handled hidden directories, and found that it also shows them. I guess I'll have to be inconsistent using the title bar to warn users and trap inappropriate selections sending the user back to try again. I can only assume that windows users don't get this problem. Do any of the other graphical packages avoid this problem? I guess I should try the appropriate news groups. Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] [Tkinter-discuss] tkinter file dialog pattern matching (fwd)
On 23/08/15 23:52, Laura Creighton wrote: oooh. Seems that there is an undocumented feature we can use! Laura --- Forwarded Message Return-Path: Date: Sun, 23 Aug 2015 12:40:02 +0200 From: Michael Lange To: tkinter-disc...@python.org Message-Id: <20150823124002.7391f37e21f9b5cfaa917...@web.de> In-Reply-To: <20150822210424.321b826f@lenny> References: <201508221103.t7mb3kdx010...@fido.openend.se> Hi, On Sat, 22 Aug 2015 21:04:24 +0100 Pawel Mosakowski wrote: Hi, I've found this little gem in the Tk docs https://www.tcl.tk/man/tcl8.4/TkCmd/getOpenFile.htm#M13 From what I see "file patterns" in the file dialog are not "regex patterns" and do not support special characters. Only things that work are: 1) * - any extension 2) "" - files without extension 3) literal extension without wildcard chars Unfortunately it looks like there is no simple way to filter out hidden files. actually the unix tk file dialog has an an (however undocumented) feature to hide hidden elements and display even a button that allows to toggle between hidden elements on/off, however we need to do a little tcl to get to this. Since the feature is not documented anywhere it might also be a good idea to wrap this into a try...except. See this little code snippet: # from Tkinter import * import tkFileDialog as tkfd root = Tk() try: # call a dummy dialog with an impossible option to initialize the file # dialog without really getting a dialog window; this will throw a # TclError, so we need a try...except : try: root.tk.call('tk_getOpenFile', '-foobarbaz') except TclError: pass # now set the magic variables accordingly root.tk.call('set', '::tk::dialog::file::showHiddenBtn', '1') root.tk.call('set', '::tk::dialog::file::showHiddenVar', '0') except: pass # a simple callback for testing: def openfile(event): fname = tkfd.askopenfilename() print(fname) root.bind('', openfile) root.mainloop() # Best regards Michael ___ Tkinter-discuss mailing list tkinter-disc...@python.org https://mail.python.org/mailman/listinfo/tkinter-discuss --- End of Forwarded Message ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Thanks Laura, That does exactly what I wanted to do. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Why does this function execute before being called?
Hi, Environment: Python 2.7 Linux (Ubuntu 15.10) I am experiencing a problem with the code below running the "genF" function on opening the second window. I expected that function to be executed on clicking the 'fill text' button. The text widget gets filled on opening the window. This is my first attempt at opening a second window, so I expect I have done something stupid. #! /usr/bin/python from Tkinter import * root=Tk() def genF(ofield): for x in range(10): ofield.insert(END, x) ofield.insert(END, "\n") def second(): main=Toplevel(root) ofield=Text(main, height=15, width=15) ofield.pack() B3=Button(main, text='exit', command=main.destroy) B3.pack() B4=Button(main, text='fill text', command=genF(ofield)) B4.pack() main.mainloop() b1=Button(root, text='open second window', command=second) b1.pack() b2=Button(root, text='exit', command=root.destroy) b2.pack() root.mainloop() Thanks, Chris ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Why does this function execute before being called?
On 07/11/15 20:18, Alan Gauld wrote: On 07/11/15 04:34, Chris Roy-Smith wrote: def genF(ofield): ... for x in range(10): def second(): main=Toplevel(root) ofield=Text(main, height=15, width=15) ofield.pack() B3=Button(main, text='exit', command=main.destroy) B3.pack() B4=Button(main, text='fill text', command=genF(ofield)) You call a function by sup[plying the parens after its name. So the function gets called here. The normal way to circumvent that in Tkinter is to use a lambda expression to defer execution, like so: B4=Button(main, text='fill text', command=lambda wgt=ofield : genF(wgt)) This certainly wasn't obvious from what I could find on the internet. Now I see an application for Lambda B4.pack() main.mainloop() I'm not sure you need the second mainloop. I think the root level mainloop will work for your window too. Just tried out leaving this second mainloop, and every works the same. I had assumed I needed to create a loop the same as the top window. Thanks for clearing up this mystery ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] is there a better way to do this?
Hi Python 3.4 Linux (ubuntu) This code does what I want. curs is the result of a mysql query data = [[" " for x in range(9)] for y in range(count)] for (ddate, mood, walk, lag, sleep) in curs: data[row][0]=ddate data[row][1]=mood data[row][2]=walk data[row][3]=lag data[row][4]=sleep row +=1 While I don't know a better way to do this, it seems a bit awkward, is there a better way? Thank you Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
On 10/05/16 12:01, Steven D'Aprano wrote: On Mon, May 09, 2016 at 06:13:32PM +1000, Chris Roy-Smith wrote: data = [[" " for x in range(9)] for y in range(count)] for (ddate, mood, walk, lag, sleep) in curs: data[row][0]=ddate data[row][1]=mood data[row][2]=walk data[row][3]=lag data[row][4]=sleep row +=1 While I don't know a better way to do this, it seems a bit awkward, is there a better way? Hmmm, it's hard to be sure because we don't really know what count is. Do you want a bunch of empty rows at the end? My guess is No. In your code above, you initialise each row with ten spaces, and only replace five of them. So assuming you need the extra five spaces: data = [record + [" "]*5 for record in curs] provided curs returns lists, rather than tuples. (If not, it's easy to just convert using `list(record)`. If you don't need the extra five columns, the code is even simpler: data = list(curs) Thank you, that's much better I thought I needed the extra columns, but I changed things to use 2 lists of lists (one generated with the above line and another to hold my calculated results) What if you do want extra blank rows? Easiest to just add them at the end: # initialise data as above, then add blanks for i in range(how_many_extra_rows): data.append([" "]*10) which can be simplified to: data.extend([[" "]*10 for i in range(how_many_extra_rows)]) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a better way to do this?
On 10/05/16 07:03, Ondřej Rusek wrote: Dne 9.5.2016 v 10:13 Chris Roy-Smith napsal(a): Hi Python 3.4 Linux (ubuntu) This code does what I want. curs is the result of a mysql query data = [[" " for x in range(9)] for y in range(count)] for (ddate, mood, walk, lag, sleep) in curs: data[row][0]=ddate data[row][1]=mood data[row][2]=walk data[row][3]=lag data[row][4]=sleep row +=1 if you want 'lists in list' (like your solution): data = [] for ddate, mood, walk, lag, sleep in curs: data += [ [ddate, mood, walk, lag, sleep] ] or 'tuples in list': data = [] for ddate, mood, walk, lag, sleep in curs: data += [ (ddate, mood, walk, lag, sleep) ] but for 'tuples in list'... simple: data = [] for record in curs: data += [record] Thanks, I hadn't considered having a second list of lists for my calculations, Your solution is the sort of thing I was looking for. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] problems using a listbox
Hi, OS: Linux Chris-X451MA 4.4.0-97-generic #120-Ubuntu SMP Tue Sep 19 17:28:18 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux Python 3.5.2 (default, Sep 14 2017, 22:51:06) I am trying to learn how to use a tkinter listbox. When I execute my experimental code, an odd index is printed immediately (output below code), index looks wrong (shouldn’t it be an integer). Also it doesn't print new values when I select an entry. --- #!/usr/bin/python3 #test listbox from tkinter import * class Dialog(Frame): def __init__(self, master): Frame.__init__(self, master) self.list = Listbox(self, selectmode=EXTENDED) self.list.pack(fill=BOTH, expand=1) self.current = None self.poll() # start polling the list def poll(self): now = self.list.curselection() if now != self.current: self.list_has_changed(now) self.current = now self.after(250, self.poll) def list_has_changed(self, selection): print ("selection is", selection) snames=('fred', 'george', 'manuel', 'john', 'eric', 'terry') master = Tk() listbox = Listbox(master) listbox.grid(row=0) for item in snames: listbox.insert(END, item) myindicator=Dialog.list_has_changed(master, listbox) mainloop() - output: --- ./listbox.py selection is .140537834621024 Thank you for any help Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problems using a listbox
On 17/10/17 20:13, Peter Otten wrote: #!/usr/bin/python3 #test listbox from tkinter import * class Dialog(Frame): def __init__(self, master): Frame.__init__(self, master) self.list = Listbox(self, selectmode=EXTENDED) self.list.pack(fill=BOTH, expand=1) self.current = None self.poll() # start polling the list def poll(self): now = self.list.curselection() if now != self.current: self.list_has_changed(now) self.current = now self.after(250, self.poll) def list_has_changed(self, selection): print ("selection is", selection) snames=('fred', 'george', 'manuel', 'john', 'eric', 'terry') master = Tk() dialog = Dialog(master) dialog.pack() for item in snames: dialog.list.insert(END, item) mainloop() Thank you, that works, I have difficulties with object oriented coding. Never used a language where I needed it. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] trouble using tkinter CheckButton
Hi, I'm a relative newcomer to object oriented programming. Operating system Linux (ubuntu 17.10) Python version 3.6 With the code below, when I click on the "list set & unset" button I get the following error. This code is my attempt at debugging a bigger program. I have broken things down to what I think is as simple as I can get. Thank you for looking at this, Regards, Chris Roy-Smith Error message: = chris@chris-X451MA:~/Scripts/python3/dvms$ ./debugString.py Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.6/tkinter/__init__.py", line 1702, in __call__ return self.func(*args) File "./debugString.py", line 26, in Button(cmember, text='list set & unset',command= lambda lines = x : SetFin(lines) ).grid(row=x, column=2) File "./debugString.py", line 7, in SetFin SetStatus[x] = var.get(x) AttributeError: 'list' object has no attribute 'get' #!/usr/bin/python3 from tkinter import * def SetFin(lines): SetStatus=[" " for i in range(lines)] for x in range(lines): SetStatus[x] = var.get(x) print (SetStatus(x)) master = Tk() NameList=[(1, 'Vivian', 'Blackwell'), (2, 'Peter ', 'Bromell'), (3, 'Nev', 'Casey'), (4, 'Claude', 'Chatwin'), (5, 'John ', 'Dennison'), (6, 'Nicolene', 'Fairbrass'), (7, 'Paul', 'Fairbrass')] #in real situation this comes from a database and is of variable length cmember=Toplevel(master) x=0 y=0 var=[IntVar() for x in range(8)] for line in NameList: for field in line: Label(cmember, text=field).grid(row=x, column=y) y+=1 #make checkbox cb=Checkbutton(cmember, text='set', variable=var[x]).grid(row=x, column=y) y=0 x+=1 Button(cmember, text='list set & unset',command= lambda lines = x : SetFin(lines) ).grid(row=x, column=2) Button(cmember, text='exit', command=cmember.destroy).grid(row=x, column=4) mainloop() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] trouble using tkinter CheckButton
On 16/01/18 22:35, Alan Gauld via Tutor wrote: On 16/01/18 04:37, Chris Roy-Smith wrote: File "./debugString.py", line 7, in SetFin SetStatus[x] = var.get(x) AttributeError: 'list' object has no attribute 'get' var=[IntVar() for x in range(8)] Here you create a list of IntVar objects. The list has no get() method - just as the error message says. You need to access the individual IntVar for your widget. I suspect you want SetStatus[x] = var[x].get() Yes, Thank you, that was the problem. other problems in my code, after correcting the get() were easy to sort out. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] thinter: can't figure out how to update a window instead of creating a new on
Hi, system: Python 3.6, LInux I have been playing around with the following code which I want to update the window, but I creates a new window (with the correct display), but I have not been able to find the solution. Perhaps I'm using the wrong key words in my searches. Thank you for any assistance, I'm hoping to learn something from this experience Regards, Chris Roy-Smith #!/usr/bin/python3 import mysql.connector from tkinter import * import pickle master = Tk() def getCfg(): fobj = open('members.pkl', 'rb') cfg = pickle.load(fobj) fobj.close() return cfg def editmember(page=1): form=Toplevel(master) form.title('test form') cfg=getCfg() QrySelectMembers='select ident, concat_ws(" " ,`given`, `surname`) as `fullname` from `details` where 1 order by `surname` asc, `given` asc limit '+str(page)+', 10' db=mysql.connector.connect(user = cfg['user'], password = cfg['password'], database = cfg['database']) cursor=db.cursor() cursor.execute(QrySelectMembers) #,(page)) MemberList=list(cursor) cursor.close() db.close ro=0 for Member in MemberList: ident=Member[0] msg='edit '+Member[1] Button(form, text=msg, command= lambda tmp=ident : EdForm(tmp)).grid(sticky=(W, E), row=ro, column=0) ro+=1 Button(form, text='exit', command=form.destroy).grid(row=ro+1, column=2) Button(form, text='next 10', command= lambda p=page+10 : editmember(p)).grid(row=ro, column=1) Button(form, text="previous 10", command= lambda p=page-10 : editmember(p)).grid(row=ro, column=0) Button(master, text='click to test', command=editmember).grid(row=0, column=0) Button(master, text='quit', command=master.destroy).grid(row=1, column=0) master.mainloop() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] tkinter code executes before function returned
Hi, System: Python 3.6, Ubuntu Linux 17.10 I am trying to get tkinter to return a number from a window, which then sets how many times to print a sign. The code does not wait till the function returns a value, resulting in the signcount variable in having a None value, giving an output like below. Note that the output "line 64 ### The required number of signs is 5 ###" only occurs after a number is input. I can use an input statement to get the desired output, but that's not good having to go to the terminal to enter the response. How can I get the printSign code to wait till getcount() returns it's value? Any help greatly appreciated. Regards, Chris Roy-Smith chris@chris-X451MA:~/Scripts/python3/dvms$ ./debug1.py line 27 ### required sign count for D is None ### Exception in Tkinter callback Traceback (most recent call last): File "/usr/lib/python3.6/tkinter/__init__.py", line 1702, in __call__ return self.func(*args) File "./debug1.py", line 28, in printSign for x in range(signcount): TypeError: 'NoneType' object cannot be interpreted as an integer line 64 ### The required number of signs is 5 ### Code: #!/usr/bin/python3 from tkinter import * import os from reportlab.lib.units import cm from reportlab.lib.pagesizes import A4 from reportlab.pdfgen import canvas from reportlab.lib.utils import ImageReader def printSign(): global gc, packages, rows myCanvas = canvas.Canvas("Signs.pdf", pagesize=A4) width, height = A4 #keep for myCanvas.rotate(90) myCanvas.setFillColorRGB(0,0,0) myCanvas.setFont("Helvetica-Bold", 400) TopMargin=-20 LeftMargin=1 Width=14 Height=19 VertPos=-15 Bottom=-1 a=[" " for i in range(rows)] i=0 sign=0 for line in packages: signcount=getcount(line[1]) print('line 27 ### required sign count for {} is {} ###'.format(line[1], str(signcount))) for x in range(signcount): #draw rectangle myCanvas.rect(LeftMargin*cm+Width*sign*cm, TopMargin*cm, Width*cm, Height*cm, stroke=0, fill=1) myCanvas.drawCentredString((LeftMargin+(0.5*Width))*cm+(Width*sign)*cm, VertPos*cm, line[0]) if sign==1: myCanvas.showPage() sign=0 myCanvas.rotate(90) i+=1 else: sign+=1 i+=1 myCanvas.showPage() myCanvas.save() if os.name == "posix": os.popen("evince %s" % ("Signs.pdf")) if os.name == "nt": os.startfile('Signs.pdf') def getcount(SignText): global gc,e gc=Toplevel(master) MsgText='How many copies of {} do you want to print?'.format(SignText) Label(gc, text=MsgText).grid(row=0, column=0, sticky=(W,E)) e = Entry(gc) e.grid(row=0, column=1) Button(gc, text='Okay', command=ReturnCount).grid(row=1, column=0, sticky=(W,E)) Button(gc, text='Cancel', command=gc.destroy).grid(row=1, column=1, sticky=(W,E)) def ReturnCount(): global gc,e b0=e.get() if b0 == None: b0=0 gc.destroy() print('line 64 ### The required number of signs is {} ###'.format(b0)) return b0 master = Tk() master.title("Testing") packages = [[0,'D','drill'],[1,'J','Jointer'],[2,'B','Bandsaw']] rows = 3 b2 = Button(master, text="Print Signs", command=printSign).grid(row=4, column=0, sticky=(W,E), padx=5, pady=5) b3 = Button(master, text="Quit", command=master.destroy).grid(row=4, column=3, sticky=(W,E)) master.mainloop() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter code executes before function returned
On 15/04/18 23:36, Alan Gauld via Tutor wrote: On 15/04/18 14:24, Alan Gauld via Tutor wrote: OK, I've had a closet look now and can confirm the A closer look! Not a closet look. Ooops! :-/ Thank you Alan, I have even more to learn than I thought. I have been bashing away at several OOP tutorials, but the penny still hasn't dropped on making that work yet, I get the concept, but don't seem to understand how to make it work for methods. Events just add to my lack of understanding. I'll have to try your tutorial. Hopefully I won't have too many questions after that. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] tkinter code executes before function returned
On 15/04/18 18:10, Alan Gauld via Tutor wrote: On 15/04/18 03:57, Chris Roy-Smith wrote: I am trying to get tkinter to return a number from a window, which then sets how many times to print a sign. I don;t jhave time to look at this in detail just now, maybe later. But first impressions is that you have a very unorthodox style of Tkinter programming. Its more traditional to build the entire GUI up front rather than creating and destroying widgets each time you execute an event handler. Its less disturbing to the user than having things appear/disappear etc, as you seem to be doing. You can make widget hide/show/deactivate themselves without destroying them just by withdrawing/unpacking them etc or changing their status, if that's really what you want to do. The code does not wait till the function returns a value, resulting in the signcount variable in having a None value, giving an output like below. I'll look at this a bit more closely later if nobody else answers by then... This is where you call your function. Looking at it quickly I think you would be as well using the standard Tkinter simpledialogs/messagebox modules to get user input. Have you looked at the simpledialogs? Thank you Alan, I didn't know of simpledialogs. That was all I needed to search documentation for these. I have now achieved what I was trying to do, with user interface as I was planning. Or better still having a static entry field on your GUI and just reading that? I'll have to figure out how to achieve that! Perhaps my intended design is not in line with modern styles? Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] how to change the command "string" on a tkinter Button?
Hi, OS is Linux, Python version is 3.6.5 I am trying to change the command of a tkinter Button in my program. Eventually I want to be able to do this to many buttons. My attempt at code brings up no error messages, but the button appears to do nothing. I really have no idea how to do this, but this is what I wrote. #!/usr/bin/python3 from tkinter import * class form(object): def __init__(self, x, reply, master, z,bu): self.x=x self.reply=reply self.master=master self.z=z self.bu=bu def change(x, reply, z, b): #f contains the alternative command (as a string) f=["lambda x=vars, txt=reply,fu=0 bu=b1 :form.change(x, txt, fu, bu)", "lambda x=vars, txt=first, fu=1 bu=b1: form.change(x, txt, fu, bu)"] for i in range(4): x[i].set(reply[i]) #attempt to change command clause set.button(f[z]) def draw(master): vars = [] label = [] button = StringVar for i in range(4): var = StringVar() vars.append(var) label.append("") label[i] = Label( master, textvariable=var, relief=RAISED ).grid(row=i, column=0) vars[i].set(first[i]) b1=Button(master, text="change", command=button).grid(row=i+1, column=0) reply=["now I don't know", "Happy birthday", "Many happy returns", "Next it's my turn",1] first=["What's your name?", "My name is Fred", "I have just had my birthday", "your's is next!",2] master=Tk() form.draw(master) master.mainloop() = How should I do this, I had worked around the problem by destroying the window and building it again, but it was pointed out that I have an unusual coding style doing this. All hints appreciated! Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to change the command "string" on a tkinter Button?
On 01/07/18 02:17, Alan Gauld via Tutor wrote: On 30/06/18 03:55, Chris Roy-Smith wrote: I am trying to change the command of a tkinter Button in my program. Eventually I want to be able to do this to many buttons. Since I'm not 100% sure if you mean the command or the label or both here is a simple example that does both... import tkinter as tk def cmd1(): print('This is command 1') def cmd2(): print('This is number 2') def swapCmd(): c = b1['command'] # kluge to get the function name from Tcl id if str(c).endswith("cmd1"): b1['command'] = cmd2 else: b1['command'] = cmd1 def swapText(): t = b1['text'] if t == "Cool": b1['text'] = "Hot" else: b1['text'] = "Cool" # make GUI top = tk.Tk() win = tk.Frame(top) win.pack() b1 = tk.Button(win,text="Cool", command=cmd1) b1.pack() b2 = tk.Button(win, text="Swap text", command=swapText) b2.pack() b3 = tk.Button(win, text="Swap cmd", command=swapCmd) b3.pack() top.mainloop() ### Thank you Alan, you have covered what I think I wanted to achieve. For me, programming is a continual learning experience, unfortunately I seem to forget nearly as much as I learn, Python is the first language I have attempted since macro assembler for CP/M. Python seems to be another world. It appears that I broke the code I started experimenting with, to try changing the command, and that may have added to my confusion. I'll play with your example to try an understand what is going on. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to change the command "string" on a tkinter Button?
On 01/07/18 02:17, Alan Gauld via Tutor wrote: On 30/06/18 03:55, Chris Roy-Smith wrote: I am trying to change the command of a tkinter Button in my program. Eventually I want to be able to do this to many buttons. Since I'm not 100% sure if you mean the command or the label or both here is a simple example that does both... import tkinter as tk def cmd1(): print('This is command 1') def cmd2(): print('This is number 2') I was hoping eventually to generate the command form the results of a database query, not knowing the exact command until run time. Perhaps what I was trying to achieve is too close to self modifying code, I was warned off this when I used to dabble in assembler. Does the same advice hold for python? def swapCmd(): c = b1['command'] # kluge to get the function name from Tcl id if str(c).endswith("cmd1"): b1['command'] = cmd2 else: b1['command'] = cmd1 I never thought to try anything like this, I was thinking more along the lines for how to change the text of a Labe.l def swapText(): t = b1['text'] if t == "Cool": b1['text'] = "Hot" else: b1['text'] = "Cool" # make GUI top = tk.Tk() win = tk.Frame(top) win.pack() b1 = tk.Button(win,text="Cool", command=cmd1) b1.pack() b2 = tk.Button(win, text="Swap text", command=swapText) b2.pack() b3 = tk.Button(win, text="Swap cmd", command=swapCmd) b3.pack() top.mainloop() ### Thank you again Alan, While your solution works, it's not how I imagined in terms of approach. Eventually I wanted to change the command of a variable number of buttons with the actual command depending on the results of a database query. I am unable to see how I can manage this in your solution style ( predetermined commands) might be difficult to achieve ( with my limited programming skills ). Your solution made me rethink what I was attempting to do, and found with a slightly modified database query, I didn't need to change the command at all. The rest of this bit of program I have already solved. Now I just have to learn a lot more about classes, and objects. again, thank you Alan. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] how to change the command "string" on a tkinter Button?
On 01/07/18 19:19, Steven D'Aprano wrote: On Sun, Jul 01, 2018 at 03:32:59PM +1000, Chris Roy-Smith wrote: Python is the first language I have attempted since macro assembler for CP/M. Python seems to be another world. Yes indeed, high-level languages like Python *are* a radically different programming experience than low-level languages like assembler. The fundamental execution and data models of the languages are *very* different: - assembler lives in a universe of bytes and words; there are few abstractions and you are dealing (very nearly) with the lowest level of flipping bits in hardware, or at least of moving bytes. - Python lives in a world of big, complex abstractions like dicts and Unicode text and even objects as complex as "web server", and the fundamental operations are multiple layers away from moving bytes. It's not surprising that this may require some re-adjustment of your mental model of how to program. those big complex bits cut down on the amount of code needed to achieve a given task. :-) It appears that I broke the code I started experimenting with, to try changing the command, and that may have added to my confusion. "Save As..." before engaging in big changes is your friend :-) yes, was supposed to be a quick experiment to test idea ;) Even better would be to learn a form of VCS (version control system) such as Mercurial (hg) or git. Depending on the text editor you are using, it may have VCS integration available. I don't know anything about these tools, I use Kate as my editor for my programming. I usually give a new number to separate versions, I'm sure there are better ways, I just haven't gone looking for them yet. Idle only looks useful for CLI stuff. Off-topic: I see you are a fellow Internode user, like me. Which part of Australia are you in, and is your internet connection giving you as much grief as mine is? I have had little trouble with Internode over the last 13 years or so. The other day is the first time I had a really slow download, went to another mirror in Western Australia, and all went as fast as I'm supposed to get (I have the slowest option of NBN, ( bronze 100) which I have never NEEDED extra bandwidth, it might be nice, but I don't use the sort of service which depends on good bandwidth, downloads can go all night for all I care). I'm not greedy though it's all very fast compared to dial up, or packet radio I'm pretty sure that Internode is *grossly* oversubscribed. E.g. when I try doing a google search, I'll usually get "Waiting for www.google.com..." which then times out about six or twelve times on average before succeeding to connect, after which it is damn near instantaneous. I search with DuckDuckGo, and rarely have any response issue with my searches. I don't think they sell my search data. I downloaded 2 GB of data in about ten minutes yesterday, not long followed by a 2K email that took *three hours* to leave my computer because the connection to Internode's mail server kept timing out. Your connection is a bit faster than mine. I've not experienced any speed issues with the email server. Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] why can use a widget assigned to a variable or just use it on it's own?
Hi, I'm trying to understand working with objects. If I have grasped things correctly a widget is an object. So why can I assign the widget, or use it stand alone? See sample code below = #!/usr/bin/python3 from tkinter import * main=Tk() # as I understand it this will create an instance of the button widget called b1 b1=Button(main, text='instantce', command= lambda b='goodbye' : print(b)).grid(row=1, column=0) # but here I haven't made an instance, but all seems well Button(main, text='test1', command=lambda a='hello' :print(a)).grid(row=0, column=0) main.mainloop() === any explanation gratefully recieved Regards, Chris ROy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] Tkinter: Can's figure out how to put a frame in a second window
Hi. running Linux, with python3.6 I am trying to learn how to put a frame on a second window. I get no errors showing in the terminal, and I get no traceback. What is happening is that the contents of the frame appear in the master window. I was expecting them to show in the second window. Also I expected the frame to be sunken, but there is no obvious signs of the frame, not even a colored background. What am I doing wrong? Thank you, Chris Roy-Smith here is my code: #! /usr/bin/python3 from tkinter import * def NewWindow(): sw=Toplevel(master) sw.title('New Window') Label(sw, text='new window').grid(row=0, column=0) sframe=Frame(sw, relief=SUNKEN, bg='red').grid(row=1, column=0) Label(sframe, text='Label in a frame').grid(row=2, column=0) Label(sframe, text='Second label in this frame').grid(row=3, column=0) Button(sw, text='close window', command=sw.destroy).grid(row=5, column=0) master=Tk() master.title('Master Window') Button(master, text='open window', command=NewWindow).grid(row=1, column=1) Button(master, text='quit', command=master.destroy).grid(row=2, column=1) Label(master, text="learning").grid(row=0, column=0) master.mainloop() ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Tkinter: Can's figure out how to put a frame in a second window
On 9/3/19 10:13 pm, Alan Gauld via Tutor wrote: On 09/03/2019 02:53, Chris Roy-Smith wrote: What is happening is that the contents of the frame appear in the master window. I was expecting them to show in the second window. Also I expected the frame to be sunken, but there is no obvious signs of the frame, not even a colored background. What am I doing wrong? Its a very common mistake in Tkinter. When you use one of the layout managers, in this case grid() the return value is always None. def NewWindow(): sw=Toplevel(master) sw.title('New Window') Label(sw, text='new window').grid(row=0, column=0) sframe=Frame(sw, relief=SUNKEN, bg='red').grid(row=1, column=0) So you are here assigning None to sframe. Label(sframe, text='Label in a frame').grid(row=2, column=0) Label(sframe, text='Second label in this frame').grid(row=3, column=0) And when you pass None as the parent to a widget Tk defaults to the root. So your widgets appear in your main window. Change the sframe line to two lines: sframe=Frame(sw, relief=SUNKEN, bg='red') sframe.grid(row=1, column=0) and all will be well except the sunken relief wont work. TYhats because the sunken form requires a border width of at least 2 pixels to be visible. So you need to add border=2 (or more) to make it work. So the final line should be: sframe=Frame(sw, border=2, relief=SUNKEN, bg='red') sframe.grid(row=1, column=0) As I say its a very common mistake and so, any time weird things happen, always check that anywhere you assign a widget to a variable you call the layout manager on a separate line. HTH Thanks Alan, Simple when you know. I remember having a similar issue with Entry widgets, Regards, Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
[Tutor] is there a graphics library for common tkinter Button functions?
Hi, Is there a "graphics library" of common button uses? that is things like forward record, back record, 1st record, last record, printer, save and the likes. I don't have very artistic abilities, so would prefer to save making my own library. Thank you Chris Roy-Smith ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] is there a graphics library for common tkinter Button functions?
On 21/3/19 10:19 am, Alan Gauld via Tutor wrote: On 20/03/19 22:43, Chris Roy-Smith wrote: Is there a "graphics library" of common button uses? that is things like forward record, back record, 1st record, last record, printer, save and the likes. The short answer is no. But you can assign any bitmap image to a button. (You can use other formats too but bitmaps are easiest in my experience!) But putting an image on the button does not give it any functionality. You need to program that yourself. HTH, Alan G. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor Thanks Alan, Yes I knew that buttons need a function to do anything. I was hoping that the wheel didn't need re-inventing. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Which is better in principle: to store (in file) calculated data or to re-calculate it upon restarting program?
On 31/7/19 2:21 am, boB Stepp wrote: I have been using various iterations of a solitaire scorekeeper program to explore different programming thoughts. In my latest musings I am wondering about -- in general -- whether it is best to store calculated data values in a file and reload these values, or whether to recalculate such data upon each new run of a program. In terms of my solitaire scorekeeper program is it better to store "Hand Number, Date, Time, Score, Total Score" or instead, "Hand Number, Date, Time, Score"? Of course I don't really need to store hand number since it is easily determined by its row/record number in its csv file. In this trivial example I cannot imagine there is any realistic difference between the two approaches, but I am trying to generalize my thoughts for potentially much more expensive calculations, very large data sets, and what is the likelihood of storage errors occurring in files. Any thoughts on this? TIA! From a scientific viewpoint, you want to keep the raw data, so you can perform other calculations that you may not have thought of yet. But that's not got much to do with programming ;) ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: https://mail.python.org/mailman/listinfo/tutor