Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tkinter Treeview selection

from Tkinter import *
from ttk import *
import tkMessageBox

class Application(Frame) :
    def selected(self):
        curItem = self.tree.focus();
        print self.tree.item(curItem)['values'][0]
        self.quit()

    def __init__(self,master = None):
        Frame.__init__(self, master)
        self.grid()

        tree = self.tree = Treeview(self,columns=('Name','Description'),show="headings",selectmode='browse')
        tree.heading("Name", text="Name")
        tree.heading("Description", text="Description")
        tree.grid(padx = 30)

        i = tree.insert('','end',values = ['0353','567'])
        tree.insert(i,'end',values = ['03535','567'])
        Button(self,text = "Submit",command = self.selected).grid()


root = Tk()
app = Application()
app.master.title("Tree view")
app.master.minsize(500, 400)
app.master.protocol(name = "WM_DELETE_WINDOW",func=app.master.quit)

app.mainloop()
root.destroy()

When I try to select "0353" in the tree view and submit it is printing '353' instead of 0353. I want the output to be "0353". I am using python 2.7

like image 225
Anon Avatar asked Jul 18 '26 23:07

Anon


1 Answers

Maybe my answer comes a bit late ( smile ) ... but ... the problem persists same way also in Python 3.9 . The reason for this problem is an automated conversion of strings to integer values by the tkinter Treeview widget ( in Python 3 Tkinter is named tkinter ).

The only way around seems to be accepting that all decimal digit only string entries are preceded by some other character (or characters) than a digit to prevent int(entry) deliver a value instead of an error. This 'header' can be then removed from the returned string value to get the desired value. Below a proposal for the changes required to achieve the desired result:

tree.insert('',tkinter.END,values = ['> 0353','> 567'])

print( self.tree.item(curItem)['values'][0][2:] )

By the way: I can remember from the old times of Excel that its users had coped with the same kind of problem of automated type conversion. The above provided solution applies also there.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!