Chris Roy-Smith | 1 Sep 04:46 2014
Picon

Problem using StringVar()

Just trying to learn to use Tkinter.

python 2.7.3  OS Ubuntu 12.4

This code
-----------------------
#!/usr/bin/python
import Tkinter
top = Tkinter.Tk()

v = top.StringVar()
Label(master, textvariable=v).pack()

v.set("hello")

top.mainloop()
---------------------------
returns this error message

Traceback (most recent call last):
   File "./hello.py", line 5, in <module>
     v = top.StringVar()
   File "/usr/lib/python2.7/lib-tk/Tkinter.py", line 1767, in __getattr__
     return getattr(self.tk, attr)
AttributeError: StringVar

Please what am I doing wrong?
Vasilis Vlachoudis | 25 Aug 16:15 2014
Picon
Picon

Text() highlight

Hi all,

I am trying to implement a small g-code editor and real time viewer in tkinter.
I am using the Text() widget as an editor, but I have troubles
in highlighting the text during editing. Its slow when editing big files.

below is the highlighting routine

The routine is scanning for all patterns and picks the next one to highlight
(found dictionary). It assigns a tag and re-scans all the tags that
became invalid (falling within the area of the the just assigned tag.
e.g. a valid command inside a comment)

Running it on the whole text file on every modification is out of the question,
it makes the editing very very slow on big files.

In order to minimize the calls, I do them with a delay of 50ms, using the after()
command during a period of inactivity and only for the 100lines following
the first one to be displayed. Still is slow and lacks interactivity.

I  would like your suggestions, on what is the best way to do the highlighting
during the editing of the code?

Thanks in advance
Vasilis


     def highlight(self):
        self._highAfter = None
        # List contains order of match with regular expression
        patterns = {"C": (r"\(.*\)",              "Blue")    ,
                "X": (r"[xX][+\-]?\d*\.?\d*", "DarkRed"  ),
                "Y": (r"[yY][+\-]?\d*\.?\d*", "DarkBlue" ),
                "Z": (r"[zZ][+\-]?\d*\.?\d*", "DarkGreen"),

                "I": (r"[iI][+\-]?\d*\.?\d*", "Maroon"),
                "J": (r"[jJ][+\-]?\d*\.?\d*", "Maroon"),
                "K": (r"[kK][+\-]?\d*\.?\d*", "Maroon"),
                "R": (r"[rR][+\-]?\d*\.?\d*", "Maroon"),

                "G": (r"[gG]\d+",             "Dark Orchid"),
                "M": (r"[mM]\d+",             "DarkGrey"),
                "F": (r"[fF][+\-]?\d*\.?\d*", "Yellow4"),
                "P": (r"[pP]\d+",             "DarkGrey") }

        for tag in patterns.keys():
            self.editor.tag_delete(tag)

        count = IntVar()
        start = self.editor.index("%d.0"%(self._highStart))
        end   = self.editor.index("%d.0"%(self._highStart+100))

        # First search for the first occurance of all patterns
        found = {}
        for tag,(pat,color) in patterns.items():
            index = self.editor.search(pat, start, end, count=count, regexp=True)
            if index != "":
                found[tag] = (index, count.get())
                #print "Found:", tag, index, count.get()

        # Main loop
        while True:
            # Find the top-most pattern to highlight
            nextTag   = None
            nextIndex = end
            nextCount = 0
            for tag,(index,c) in found.items():
                if self.editor.compare(index,"<",nextIndex):
                    nextTag   = tag
                    nextIndex = index
                    nextCount = c

            #print "Minimum:", nextTag, nextIndex, nextCount
            if nextTag is None: break
            start = self.editor.index("%s+%sc"%(nextIndex,nextCount))
            self.editor.tag_add(nextTag, nextIndex, start)

            # Update tags
            foundItems = found.items()
            for tag,(index,c) in foundItems:
                #print ">>",tag,index
                if self.editor.compare(index,"<",start):
                    index = self.editor.search(patterns[tag][0],
                            start, end,
                            count=count,
                            regexp=True)
                    if index != "":
                        #print "Update:", tag, index, count.get()
                        found[tag] = (index, count.get())
                    else:
                        #print "Update:", tag, "-None-"
                        del found[tag]

        # Set properties to tags
        for tag,(pat,color) in patterns.items():
            self.editor.tag_config(tag,foreground=color)

    # ----------------------------------------------------------------------
    def highlightAfter(self):
        if self._highAfter is not None: self.after_cancel(self._highAfter)
        self._highAfter = self.after(10, self.highlight)

_______________________________________________
Tkinter-discuss mailing list
Tkinter-discuss <at> python.org
https://mail.python.org/mailman/listinfo/tkinter-discuss
JBB | 12 Aug 05:37 2014
Picon

tkFileDialog.askopenfile() mac

Hello,

I am attempting to use tkFileDialog.askopenfile():

1) On my Mac OSX Mavericks w/ Python 2.7.8, Anaconda 2.0.1 (x86_64) the 
following code (found via web searches) crashes:

from Tkinter import *
import tkFileDialog
root = Tk()
root.withdraw()
file = tkFileDialog.askopenfile(parent=root)

- A file dialog opens, I can select a file and click the Open button or 
doubleclick the filename.  The window freezes, the spinning rainbow ball 
comes up, and a Kernel restart is needed to close the window.

This happens on iPython notebook as well as within the Spyder IDE.

2) I run the same distribution on a Linux VM on the same machine. 
There, it works fine.  The variable 'file' contains the name of 
whichever file I've selected.

As far as I know, my Mac Python distribution is up-to-date.

Pointers to documentation or fixes appreciated.

JBB
Bob Greschke | 19 Jul 00:54 2014

Combining events?

I have a huge program...several huge programs...and I keep writing duplicate sets of calls for <Return>
and <KP_enter>.  I'm tired of it, even though they are already all written.  Is there any way to combine those
(those two, specifically) into one bind like

x.bind(("<Return>", "<KP_Enter"), command = .....?

I know you can't do that, but something like that on a global scale (both figuratively, and
programmatically).  Some little line of code at the beginning of the program that redirects the
<KP_Enter> to the <Return> event when some field or whatever is specifically looking for either return
key to be pressed?.

Thanks!
Alan Gauld | 23 Jun 00:18 2014

divergent behaviour

I've observed a strange difference in the behaviour of
one of my event handlers, I'm wondering if anyone knows
the explanation.

I have a form with a list box and a set of buttons.
When you highlight a list item you can press the
Edit button and it calls evEdit() which opens an
edit dialog in the centre of the parent window.

However I also bound the double click event to evEdit and
if you double click the same item it opebns the dialog
in the centre of the screen.

Does anyone know why double-click and button versions
of the same method result in different locations? I'm
assuming that somehow the dialog (TopLevel widget) sees
the screen as its parent in one version but the
original window as parent in the other - maybe...?

PS.
If necessary I'll try to produce a short example to
illustrate, but the existing code is over 500 lines
so a tad too long to post.

--

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
Thiago Padilha | 10 Jun 23:59 2014
Picon

Text widget "lags" when doing fast updates with increased window heights

I'm currently implementing a sample UI for neovim(http://neovim.org/),
and decided to use Tkinter/python due to the popularity/simplicity of
the platforms. The problem I'm having is that tkinter seems to "stack"
UI updates when the window height crosses a certain threshold.

Here is a video that shows the problem: http://youtu.be/sgE2C9lLqQQ

The right window is a terminal emulator running neovim, and the left
window is the Tkinter UI program connected to neovim. The idea is that
the tkinter UI should mirror neovim terminal screen, including
dimensions. Notice that in this video I don't take focus away from the
terminal window, so the only events Tk has to process come from the
connection to neovim(virtual <<nvim>> events which describe screen
updates)

The first part of the video shows that everything works nicely when
the window height is small, but starts to lag updates when I increase
the height.

I think what I'm trying to implement is close to a terminal
emulator(must handle large bursts of text updates efficiently) but I'm
very inexperienced in GUI programming. Is Tkinter a wise choice for
this task? If yes, then what am I doing wrong?(

The code for the Tkinter program is here: http://pastebin.com/0c8cjsmR
and my OS is ubuntu 12.04(running as a VM under windows 7)

Thanks in advance

Thiago.
Saimadhav Heblikar | 8 Jun 15:55 2014
Picon

About making Text.tag_*range methods more consistent

Some code,

>>> from tkinter import Text
>>> text = Text()
>>> text.pack()
>>> text.insert('insert', 'ab cd ef')
>>> text.tag_add('red', '1.0','1.2')
>>> text.tag_add('red', '1.6', '1.8')
>>> text.tag_prevrange('red', 'end')
('1.6', '1.8')
>>> text.tag_ranges('red')
(<textindex object: '1.0'>, <textindex object: '1.2'>, <textindex object: '1.6'>, <textindex object: '1.8'>)
>>> text.tag_nextrange('red', '1.0')
('1.0', '1.2')

I propose that Text.tag_ranges(tag) return a list of tuples (start index, end index), instead of a list like [start index1, endindex1, startindex2, endindex2....etc]

To be more even more consistent, tag_ranges tuples should contain indexes similar to the ones returned by tag_prevrange/tag_nextrange i.e. strings instead of textindex objects.

So, the above output would have been
>>> text.tag_ranges('red')
(('1.0', '1.2'), ('1.6', '1.8'))

If there is a reason for current behavior, can you link me to it?
-- 
Regards
Saimadhav Heblikar
_______________________________________________
Tkinter-discuss mailing list
Tkinter-discuss <at> python.org
https://mail.python.org/mailman/listinfo/tkinter-discuss
Alan Gauld | 13 May 20:51 2014

How to enable/disable a menu?

I have an app with a tabbed notebook. I want to
only enable one of the main menus when the appropriate
tab is selected. When the tab is deselected I want
to disable the menu again.

I can't see any obvious properties in the Menu
object. I can mess around with flags in the event
handlers and change the menu font colours etc but
that's pretty horrible. Is there anything better?

Using Python 3.3; on Linux and Windows 8 if it makes
any difference.

TIA
--

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
Josef Eschgfaeller | 9 May 23:35 2014
Picon

Different fonts in 3.3?

Trying to pass from Python 3.1 to 3.3 I have
a problem with Tkinter: fonts (or spacings)
in 3.3 seem to be higher, so that after
instructions like

    A=tkinter.Text(B,width=36,height=27,...)

the text widget requires more space than
before with 3.1. I have Mac OS X 10.6.8 and
call Python from a script using

    #! /Library/Frameworks/Python.framework\
                /Versions/3.x/bin/python3

It seems also that the letters are a bit uglier,
somewhat more compressed.

Thanks
Josef Eschgfaeller
Alan Gauld | 20 Apr 19:30 2014

Is this the right place for Tix questions?

I don't see a separate Tix group so is this a valid place
to ask Tix questions? I've been trying to use some of
the Tix widgets and running into issues, especially
with tix.Grid formatting.

--

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos
GKalman | 15 Mar 02:20 2014
Picon
Picon

Need help using Tkinter Widget lift() and lower() methods with Place geometry Manager

"""
I tried a simple case:
Frame with two Canvas widgets. I drag (i.e. move) Canvas #1. When it
overlaps with Canvas #2 neither the lift() nor the lower() methods work.
Why? 
"""
from Tkinter import *

class myObject():
    #--------------------------------
    def __init__(self,root):
        self.root = root

        #place a Frame on the root:
        self.f = Frame(self.root, bg="yellow", width=600, height=400)
        self.f.pack()

        #place a Canvas on the Frame:
        self.c =Canvas(self.f, bg="cyan",width=100,height=50)
        #NW-vtx of Canvas:
        self.xNW=10
        self.yNW=10
        self.c.place(x=self.xNW,y=self.yNW)

        ##event-generators:
        self.c.bind('<ButtonPress-1>', self.startMoveWindow)
        self.c.bind('<B1-Motion>', self.MoveWindow)

        self.c2=Canvas(self.f,bg="red",width=100,height=100)
        self.c2.place(x=300,y=200)
        self.c2.lower(self.c)

    #-----------------------------------------------
    def startMoveWindow(self, event):
        ## at start: record current root coordinates
        self.xo, self.yo = event.x_root, event.y_root

    #--------------------------------------
    def MoveWindow(self, event):
        self.root.update_idletasks()

        ## use root coordinates for offset of Widget (canvas) coordinates
        self.xNW += event.x_root - self.xo
        self.yNW+= event.y_root - self.yo
        ## update coordinates
        self.xo, self.yo= event.x_root, event.y_root

        ## Move & redraw Widget (canvas)
        self.c.place_configure(x=self.xNW, y=self.yNW)

#==================================
root=Tk()
x = myObject(root)
root.mainloop()

--
View this message in context: http://python.6.x6.nabble.com/Need-help-using-Tkinter-Widget-lift-and-lower-methods-with-Place-geometry-Manager-tp5050511.html
Sent from the Python - tkinter-discuss mailing list archive at Nabble.com.

Gmane