tkinter, unable to call a function from outside of it's class - python

Put simply, i cannot call filterCBOs from the marked problem area within my program. It returns:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Anaconda\envs\SE_win64_py35\lib\tkinter\__init__.py", line 1550, in __call__
return self.func(*args)
File "<ipython-input-24-b9ade6a4c197>", line 116, in callFilters
Root.filterCBOs(self)
File "<ipython-input-24-b9ade6a4c197>", line 164, in filterCBOs
startDate = dt.datetime(year=int(self.fromDate.get()[2]),month=int(self.fromDate.get()[0]),day=int(self.fromDate.get()[1]))
AttributeError: 'Event' object has no attribute 'fromDate'
As you can see, this function works exactly as it should when it is called within init as well as when it is called by selecting a combobox value. It however does not work when it is called by binding the enter key to the entry fields within DateEntry. I am brand new to classes so im sure its something to do with it being called from within another class but I am lost as to how to navigate around this.
#================================================================================
# Imports
#================================================================================
import os
import pandas as pd
import datetime as dt
import tkinter as tk
from tkinter import ttk
startTimestamp=dt.datetime.now()
print('Starting ' + str(startTimestamp))
#================================================================================
# User Changable Variables
#================================================================================
#signaturePath = r'T:\Process Data\EDM\Signature Files'
#================================================================================
# Functions (mostly used to cleanup variables)
#================================================================================
#commented out because i ran this section once and saved to csv. saves me from indexing
#the directory during testing.
'''
def indexDirectory():
#filenames use the following format:
# yyyy.mm.dd.hh.mm.tool.toolSN.feature.sfc.sig
df = pd.DataFrame(columns=['FullPath', 'Timestamp', 'Feature', 'Machine', 'Tool'])
for root, dirs, files in os.walk(signaturePath):
for file in files:
splitter = file.split('.')
if len(splitter) != 10: #weird filename
continue #skip to next file
date=dt.datetime.strptime(splitter[0]+'-'+splitter[1]+'-'+splitter[2]+' '+splitter[3]+':'+splitter[4],'%Y-%m-%d %H:%M')
df = df.append({'FullPath' : os.path.join(root, file), \
'Timestamp' : date, \
'Feature' : splitter[7], \
'Machine' : os.path.basename(root), \
'Tool' : splitter[5] + '_' + splitter[6] \
}, ignore_index=True)
return df
with open(r'C:\Users\u1106710\Desktop\Index.csv', 'w+') as SaTemp:
indexDirectory().to_csv(SaTemp, header=True, index=False)
'''
# Index available signature files to a dataframe
#sigIndex=indexDirectory
sigIndex=pd.read_csv(r'D:\Tibbert\4) Scripts\Signature Analysis\Temp\Index.csv')
sigIndex['Timestamp'] = pd.to_datetime(sigIndex['Timestamp'])
#================================================================================
# Build GUI
#================================================================================
class DateEntry(tk.Frame):
def __init__(self, master, frame_look={}, **look):
args = dict(relief=tk.SUNKEN, border=1)
args.update(frame_look)
tk.Frame.__init__(self, master, **args)
args = {'relief': tk.FLAT}
args.update(look)
self.entry_1 = tk.Entry(self, width=2, **args)
self.label_1 = tk.Label(self, text='/', **args)
self.entry_2 = tk.Entry(self, width=2, **args)
self.label_2 = tk.Label(self, text='/', **args)
self.entry_3 = tk.Entry(self, width=4, **args)
self.entry_1.pack(side=tk.LEFT)
self.label_1.pack(side=tk.LEFT)
self.entry_2.pack(side=tk.LEFT)
self.label_2.pack(side=tk.LEFT)
self.entry_3.pack(side=tk.LEFT)
self.entries = [self.entry_1, self.entry_2, self.entry_3]
self.entry_1.bind('<KeyRelease>', lambda e: self._check(0, 2))
self.entry_2.bind('<KeyRelease>', lambda e: self._check(1, 2))
self.entry_3.bind('<KeyRelease>', lambda e: self._check(2, 4))
#PROBLEM HERE!
#self.entry_1.bind('<Return>', Root.filterCBOs)
#self.entry_2.bind('<Return>', Root.filterCBOs)
#self.entry_3.bind('<Return>', Root.filterCBOs)
def _backspace(self, entry):
cont = entry.get()
entry.delete(0, tk.END)
entry.insert(0, cont[:-1])
def _check(self, index, size):
entry = self.entries[index]
next_index = index + 1
next_entry = self.entries[next_index] if next_index < len(self.entries) else None
data = entry.get()
if len(data) > size or not data.isdigit():
self._backspace(entry)
if len(data) >= size and next_entry:
next_entry.focus()
def get(self):
return [e.get() for e in self.entries]
class Root(tk.Tk):
def __init__(self):
super(Root, self).__init__()
self.title("Filmcool Siganture Analysis")
self.minsize(width=800,height=600)
self.InitUI()
self.filterCBOs()
def InitUI(self):
#Setup Date Entry
self.fromDateLBL = tk.Label(self, text='Date Range')
self.fromDate = DateEntry(self)
self.toDateLBL = tk.Label(self, text='To')
self.toDate = DateEntry(self)
#Set Date Defaults
self.fromDate.entry_1.insert(0,'01')
self.fromDate.entry_2.insert(0,'01')
self.fromDate.entry_3.insert(0,'2014')
self.toDate.entry_1.insert(0,dt.date.today().month)
self.toDate.entry_2.insert(0,dt.date.today().day)
self.toDate.entry_3.insert(0,dt.date.today().year)
#Setup Feature Combobox
self.featureLBL = tk.Label(self, text='Feature')
self.featureCBO = ttk.Combobox(self, width=15)
self.featureCBO.bind('<<ComboboxSelected>>', self.filterCBOs)
#Setup Tool Combobox
self.toolLBL = tk.Label(self, text='Tool')
self.toolCBO = ttk.Combobox(self, width=15)
self.toolCBO.bind('<<ComboboxSelected>>', self.filterCBOs)
#Arrange UI Elements
self.fromDateLBL.grid(column=0,row=4)
self.fromDate.grid(column=1,row=4,sticky='e')
self.toDateLBL.grid(column=2,row=4,sticky='e')
self.toDate.grid(column=3,row=4)
self.featureLBL.grid(column=0, row=0, sticky='w')
self.featureCBO.grid(column=1, row=0)
self.toolLBL.grid(column=0, row=1, sticky='w')
self.toolCBO.grid(column=1, row=1)
def filterCBOs(self, event=None):
#Create and filter dataframe
df=sigIndex
#Filter by Date
#THROWS ERROR ON NEXT LINE
startDate = dt.datetime(year=int(self.fromDate.get()[2]),month=int(self.fromDate.get()[0]),day=int(self.fromDate.get()[1]))
endDate = dt.datetime(year=int(self.toDate.get()[2]),month=int(self.toDate.get()[0]),day=int(self.toDate.get()[1]))
print(startDate)
print(endDate)
df=df[(df['Timestamp'] >= startDate) & (df['Timestamp'] <= endDate)]
#Filter by Feature
if self.featureCBO.get() == "":
pass
else:
df=df[df['Feature'] == self.featureCBO.get()]
#Filter by Tool
if self.toolCBO.get() == "":
pass
else:
df=df[df['Tool'] == self.toolCBO.get()]
#print(df)
#Filter Feature CBO
self.featureCBO['values'] = df['Feature'].unique().tolist()
self.featureCBO['values'] = (*self.featureCBO['values'], '') #add empty line to end
#Filter Tool CBO
self.toolCBO['values'] = df['Tool'].unique().tolist()
self.toolCBO['values'] = (*self.toolCBO['values'], '') #add empty line to end
if __name__ == '__main__':
window = Root()
window.mainloop()
print('done')

The problem is with trying to reference the function as Root.filterCBOs). The function belongs to an instance of Root, so it needs to bemaster.filterCBOssincemaster` is being set to the root window.
self.entry_1.bind('<Return>', master.filterCBOs)

Related

Associate idle keyboard events to widget text tkinter

I am trying to create my own python code editor. For that I tried to use the tkcode module. Tkcode partially covers my needs (colors in the text for example), but it does not have the keyboard events that Idle has (automatic indentation when pressing enter, when pressing tab puts 4 spaces, etc). Some of them I can try to recreate, but automatic indentation is difficult. Is there any way to associate the Idle events to my code editor using the idlelib without creating another window (since I am making a notebook)? I went through the source code of Idle and couldn't find the way.
I know that this site is not to ask for recommendations, but if you recommend a better module to create a text widget that allows me to create this editor, it would be great too.
This is the code I have made:
from tkcode import CodeEditor
from tkinter import ttk
import tkinter as tk
import re
class CodeEditor(CodeEditor):
def __init__(Self, *args, **kargs):
super().__init__(*args, **kargs)
Self.bind("<Return>", Self.enter)
def get_current_line(Self):
return Self.get("insert linestart", "insert lineend")
def enter(Self, event):
for index, char in enumerate(Self.get_current_line()):
if(char != " "):
break
else:
index += 1
Self.insert("insert", "\n")
Self.insert("insert", " "*index)
return "break"
class FileHandler:
def __init__(Self, progs_path, filetabs):
Self.files = {}
Self.progs_path = progs_path
Self.filetabs = filetabs
def askopen(Self):
v = tk.Toplevel()
v.transient()
v.resizable(0, 0)
prog = ttk.Entry(v)
prog.pack(padx=10, pady=10)
prog.bind("<Return>", lambda Event:(Self.open(prog.get()), v.destroy()))
def open(Self, prog):
progfile = str(prog)[0]
progfile = f"prog{progfile}00A{progfile}99.py"
if(progfile in Self.files):
text = Self.files[progfile][prog]
else:
functions = {}
name = None
with open(f"{Self.progs_path}/{progfile}") as file:
for line in file:
match = re.match("(def|class) prog(\w+)", line)
if(match):
name = match[2]
functions[name] = line
if(line.startswith(" ") and name):
functions[name] += line
Self.files[progfile] = functions
text = functions[prog]
frame = ttk.Frame(Self.filetabs)
code_editor = CodeEditor(frame, language="python", highlighter="mariana", font="TkFixedFont", autofocus=True, padx=10, pady=10)
code_editor.pack(fill="both", expand=True)
code_editor.content = text
Self.filetabs.add(frame, text="prog"+prog)
v = tk.Tk()
filetabs = ttk.Notebook()
fh = FileHandler(".", filetabs)
menubar = tk.Menu(tearoff=0)
file = tk.Menu(tearoff=0)
menubar.add_cascade(label="Archivo", menu=file)
file.add_command(label="Abrir prog", command=fh.askopen)
v["menu"] = menubar
filetabs.pack(fill="both", expand=True)
fh.open("833")
In the end I was able to fix it. I was able to recreate almost all but one of the functions. For the last one, I made an impersonator class for idlelib.editor.EditorWindow to be able to do the automatic indentation, in addition to adding two new functions to the tkcode.CodeEditor.
However, I find this solution to be very unstable. Any better answer is still appreciated c:
This is the code:
from tkcode import CodeEditor
from tkinter import ttk
from idlelib.editor import EditorWindow
import tkinter as tk
import re
class FakeEditorWindow(EditorWindow):
def __init__(Self, text):
Self.text = text
Self.indentwidth = 4
Self.tabwidth = 4
Self.prompt_last_line = ''
Self.num_context_lines = 50, 500, 5000000
Self.usetabs = False
def is_char_in_string(Self, text_index):
return 1
class CodeEditor(CodeEditor):
def __init__(Self, *args, **kargs):
super().__init__(*args, **kargs)
Self.fake_editor_window = FakeEditorWindow(Self)
Self.bind("<Tab>", Self.tab)
Self.bind("<Control-Shift_L>", Self.dedent)
Self.bind("<BackSpace>", Self.backspace)
Self.bind("<Home>", Self.inicio)
Self.bind("<Return>", Self.enter)
def undo_block_start(Self):
pass
def undo_block_stop(Self):
pass
def get_current_line(Self):
return Self.get("insert linestart", "insert lineend")
def selection_get(Self):
if(Self.tag_ranges("sel")):
return Self.get("sel.first", "sel.last")
else:
return ""
def get_selection_zone(Self):
return (map(int, Self.index('sel.first').split(".", 1)),
map(int, Self.index('sel.last').split(".", 1)))
def tab(Self, event):
selection = Self.selection_get()
if(selection):
(startline, startcolumn), (endline, endcolumn) = Self.get_selection_zone()
if(startcolumn == 0):
for line in range(startline, endline+1):
Self.insert(f"{line}.0", " "*4)
Self.tag_add("sel", f"{startline}.0", "sel.last")
Self.mark_set("insert", f"{endline+1}.0")
else:
Self.insert("insert", " "*4)
return "break"
def dedent(Self, event):
if(Self.tag_ranges("sel")):
(startline, startcolumn), (endline, endcolumn) = Self.get_selection_zone()
if(startcolumn == 0):
for line in range(startline, endline+1):
if(Self.get(f"{line}.0", f"{line}.4") == " "*4):
Self.delete(f"{line}.0", f"{line}.4")
def backspace(Self, event):
if(not Self.tag_ranges("sel") and Self.get("insert linestart", "insert").isspace()):
cursor_line, cursor_col = map(int, Self.index("insert").split(".", 1))
Self.delete(f"{cursor_line}.{cursor_col-4}", "insert")
return "break"
def inicio(Self, event):
cursor_line, cursor_column = map(int, Self.index('insert').split(".", 1))
if(not Self.get("insert linestart", f"{cursor_line}.{cursor_column}").isspace()):
for i in range(cursor_column, -1, -1):
if(Self.get("insert linestart", f"{cursor_line}.{i}").isspace()):
Self.mark_set("insert", f"{cursor_line}.{i}")
return "break"
def enter(Self, event):
return EditorWindow.newline_and_indent_event(Self.fake_editor_window, event)
class FileHandler:
def __init__(Self, progs_path, filetabs):
Self.files = {}
Self.progs_path = progs_path
Self.filetabs = filetabs
def askopen(Self):
v = tk.Toplevel()
v.transient()
v.resizable(0, 0)
prog = ttk.Entry(v)
prog.pack(padx=10, pady=10)
prog.bind("<Return>", lambda Event:(Self.open(prog.get()), v.destroy()))
def open(Self, prog):
progfile = str(prog)[0]
progfile = f"prog{progfile}00A{progfile}99.py"
if(progfile in Self.files):
text = Self.files[progfile][prog]
else:
functions = {}
name = None
with open(f"{Self.progs_path}/{progfile}") as file:
for line in file:
match = re.match("(def|class) prog(\w+)", line)
if(match):
name = match[2]
functions[name] = line
if(line.startswith(" ") and name):
functions[name] += line
Self.files[progfile] = functions
text = functions[prog]
frame = ttk.Frame(Self.filetabs)
code_editor = CodeEditor(frame, language="python", highlighter="mariana", font="TkFixedFont", autofocus=True, padx=10, pady=10)
code_editor.pack(fill="both", expand=True)
code_editor.content = text
Self.filetabs.add(frame, text="prog"+prog)
v = tk.Tk()
filetabs = ttk.Notebook()
fh = FileHandler(".", filetabs)
menubar = tk.Menu(tearoff=0)
file = tk.Menu(tearoff=0)
menubar.add_cascade(label="Archivo", menu=file)
file.add_command(label="Abrir prog", command=fh.askopen)
v["menu"] = menubar
filetabs.pack(fill="both", expand=True)
fh.open("833")

How to use Python oops concepts to develop dual pane file browser? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I am trying to create a dual-pane file browser using python and Tkinter GUI to which I will be adding functions like 'compare directories', 'compare files' on a button click.
(The final GUI looks somewhat like this tool called Meld https://en.wikipedia.org/wiki/Meld_(software))
As a first step, I am trying to create a Tree() class (whose script is written in Tree_browser.py). Then I am importing this
using import Tree_browser into dircmp_utility.py. (I will also be writing one more script for directory/file comparison called dircmp.py)
Now my problem is I am new to class & oops concepts and still trying to learn & understand. So after spending some time over the internet(YouTube, StackOverflow, geeks for geeks, etc..), I tried the below code for which I am getting below shown errors.
Can someone please tell me why I am getting this error and what is the mistake in my code
Even though self, autoscroll(), populate_roots() are defined it is throwing an error saying they are not defined. Why is this??
Tree_browser.py
import os
import glob
import tkinter as tk
from tkinter import ttk
class Tree():
def __init__(self,root):
self.frame = tk.Frame(root)
self.frame.pack()
def populate_tree(self, tree, node):
if tree.set(node, "type") != 'directory':
return
path = tree.set(node, "fullpath")
tree.delete(*tree.get_children(node))
parent = tree.parent(node)
special_dirs = [] if parent else glob.glob('.') + glob.glob('..')
for p in special_dirs + os.listdir(path):
ptype = None
p = os.path.join(path, p).replace('\\', '/')
if os.path.isdir(p): ptype = "directory"
elif os.path.isfile(p): ptype = "file"
fname = os.path.split(p)[1]
id = tree.insert(node, "end", text=fname, values=[p, ptype])
if ptype == 'directory':
if fname not in ('.', '..'):
tree.insert(id, 0, text="dummy")
tree.item(id, text=fname)
elif ptype == 'file':
size = os.stat(p).st_size
tree.set(id, "size", "%d bytes" % size)
def populate_roots(self, tree):
self.dir = os.path.abspath('.').replace('\\', '/')
self.node = tree.insert('', 'end', text=dir, values=[dir, "directory"])
populate_tree(tree, node)
def update_tree(self, event):
tree = event.widget
populate_tree(tree, tree.focus())
def change_dir(self,event):
tree = event.widget
node = tree.focus()
if tree.parent(node):
path = os.path.abspath(tree.set(node, "fullpath"))
if os.path.isdir(path):
os.chdir(path)
tree.delete(tree.get_children(''))
populate_roots(tree)
def autoscroll(self, sbar, first, last):
"""Hide and show scrollbar as needed."""
first, last = float(first), float(last)
if first <= 0 and last >= 1:
sbar.pack_forget()
else:
sbar.pack()
sbar.set(first, last)
vsb = ttk.Scrollbar(orient="vertical")
hsb = ttk.Scrollbar(orient="horizontal")
tree = ttk.Treeview(self.frame, columns=("fullpath", "type", "size"),
displaycolumns="size", yscrollcommand=lambda f, l: autoscroll(vsb, f, l),
xscrollcommand=lambda f, l:autoscroll(hsb, f, l))
tree.pack()
vsb['command'] = tree.yview
hsb['command'] = tree.xview
tree.heading("#0", text="Directory Structure", anchor='w')
tree.heading("size", text="File Size", anchor='w')
tree.column("size", stretch=0, width=100)
populate_roots(tree)
tree.bind('<<TreeviewOpen>>', update_tree)
tree.bind('<Double-Button-1>', change_dir)
# Arrange the tree and its scrollbars in the toplevel
tree.pack(expand=1, fill=BOTH)
vsb.pack(expand=1, fill=Y)
hsb.pack(expand=1, fill=X)
if __name__ == '__main__':
pass
dircmp_utility.py
import Tree_browser
import dircmp
import tkinter
master = tk()
left_frame = Frame(master)
right_frame = Frame(master)
left_frame.pack()
right_frame.pack()
left_tree = Tree(left_frame)
right_tree = Tree(right_frame)
master.mainloop()
Errors after running dircmp.py
Traceback (most recent call last):
File "E:\Python_code_to_compare_two_folders\dircmp_using class\dircmp_utility.py", line 3, in <module>
import Tree_browser
File "E:\Python_code_to_compare_two_folders\dircmp_using class\Tree_browser.py", line 7, in <module>
class Tree():
File "E:\Python_code_to_compare_two_folders\dircmp_using class\Tree_browser.py", line 82, in Tree
populate_roots(tree)
TypeError: populate_roots() missing 1 required positional argument: 'tree'
>>> Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "E:\Python_code_to_compare_two_folders\dircmp_using class\Tree_browser.py", line 73, in <lambda>
xscrollcommand=lambda f, l:autoscroll(hsb, f, l))
NameError: name 'autoscroll' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python38\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "E:\Python_code_to_compare_two_folders\dircmp_using class\Tree_browser.py", line 72, in <lambda>
displaycolumns="size", yscrollcommand=lambda f, l: autoscroll(vsb, f, l),
NameError: name 'autoscroll' is not defined
File "E:\Python_code_to_compare_two_folders\dircmp_using class\Tree_browser.py", line 71, in Tree
tree = ttk.Treeview(self.frame, columns=("fullpath", "type", "size"),
NameError: name 'self' is not defined
UPDATE: Posting WORKING SCRIPT
Keeping the incorrect code which I posted earlier as it is so that others can learn from my mistakes. Thanks for all the comments which actually did help me to write the correct script.
Tree_browser.py
import os
import glob
import tkinter as tk
from tkinter import ttk
class Tree:
def __init__(self,root):
self.pane = tk.Frame(root, bg="red")
self.frame = tk.Frame(self.pane, bg="blue")
self.vsb = ttk.Scrollbar(self.frame, orient="vertical")
self.hsb = ttk.Scrollbar(self.pane, orient="horizontal")
self.tree = ttk.Treeview(self.frame, columns=("fullpath", "type", "size"),
displaycolumns="size", yscrollcommand=lambda f, l: self.yautoscroll(self.vsb, f, l),
xscrollcommand=lambda f, l: self.xautoscroll(self.hsb, f, l))
self.vsb['command'] = self.tree.yview
self.hsb['command'] = self.tree.xview
self.tree.heading("#0", text="Directory Structure", anchor='w')
self.tree.heading("size", text="File Size", anchor='w')
self.tree.column("size", stretch=0, width=100)
self.populate_roots(self.tree)
self.tree.bind('<<TreeviewOpen>>', self.update_tree)
self.tree.bind('<Double-Button-1>', self.change_dir)
# Arrange the tree and its scrollbars in the toplevel
self.pane.pack(side=tk.BOTTOM, expand=1, fill=tk.BOTH)
self.frame.pack(side=tk.TOP, expand=1, fill=tk.BOTH)
self.tree.pack(side=tk.LEFT, expand=1, fill=tk.BOTH)
self.vsb.pack(expand=1, fill=tk.Y)
self.hsb.pack(expand=1, fill=tk.X)
def populate_tree(self, tree, node):
if self.tree.set(self.node, "type") != 'directory':
return
self.path = self.tree.set(self.node, "fullpath")
self.tree.delete(*self.tree.get_children(self.node))
self.parent = self.tree.parent(self.node)
self.special_dirs = [] if self.parent else glob.glob('.') + glob.glob('..')
for p in self.special_dirs + os.listdir(self.path):
ptype = None
p = os.path.join(self.path, p).replace('\\', '/')
if os.path.isdir(p): ptype = "directory"
elif os.path.isfile(p): ptype = "file"
self.fname = os.path.split(p)[1]
id = tree.insert(self.node, "end", text=self.fname, values=[p, ptype])
if ptype == 'directory':
if self.fname not in ('.', '..'):
self.tree.insert(id, 0, text="dummy", open=True)
self.tree.item(id, text=self.fname)
elif ptype == 'file':
size = os.stat(p).st_size
self.tree.set(id, "size", "%d bytes" % size)
def populate_roots(self, tree):
self.dir = os.path.abspath('.').replace('\\', '/')
self.node = tree.insert('', 'end', text=self.dir, values=[self.dir, "directory"], open=True)
self.populate_tree(self.tree, self.node)
def update_tree(self, event):
self.tree = event.widget
self.node = self.tree.focus()
self.populate_tree(self.tree, self.node)
def change_dir(self,event):
self.tree = event.widget
self.node = self.tree.focus()
if self.tree.parent(self.node):
self.path = os.path.abspath(self.tree.set(self.node, "fullpath"))
if os.path.isdir(self.path):
os.chdir(self.path)
self.tree.delete(self.tree.get_children(''))
self.populate_roots(self.tree)
def yautoscroll(self, sbar, first, last):
"""Hide and show scrollbar as needed."""
self.first, self.last = float(first), float(last)
if self.first <= 0 and self.last >= 1:
sbar.pack_forget()
else:
sbar.pack(side=tk.LEFT, fill=tk.BOTH, expand=0)
sbar.set(self.first, self.last)
def xautoscroll(self, sbar, first, last):
"""Hide and show scrollbar as needed."""
self.first, self.last = float(first), float(last)
if self.first <= 0 and self.last >= 1:
sbar.pack_forget()
else:
sbar.pack(side=tk.LEFT, fill=tk.BOTH, expand=1)
sbar.set(self.first, self.last)
if __name__ == '__main__':
pass
dircmp_utility.py
import tkinter as tk
master = tk.Tk()
left_frame = tk.Frame(master)
right_frame = tk.Frame(master)
left_frame.pack(side=tk.LEFT, expand=1, fill=tk.BOTH)
right_frame.pack(side=tk.LEFT, expand=1, fill=tk.BOTH)
left_tree = Tree(left_frame)
right_tree = Tree(right_frame)
master.mainloop()
Let's extract your class profile, one function profile, and the erroneous statement:
class Tree():
...
...
def autoscroll(self, sbar, first, last):
...
...
tree = ttk.Treeview(self.frame, columns=("fullpath", "type", "size"),
displaycolumns="size", yscrollcommand=lambda f, l: autoscroll(vsb, f, l),
xscrollcommand=lambda f, l:autoscroll(hsb, f, l))
You seem to be a bit confused about the structure of a class. The 3-line statement above is in the body of your class. It is not within an instance method -- so there is no symbiont instance, and no self variable is defined.
Later in the same statement, you try to call an "open" function, autoscroll. There is no such function. You are confusing this with the instance method of the same name. Look up how to call an instance method -- it would be something continaing
seedling = Tree()
...
seedling.autoscroll(vsb, f, l)
Back up a few steps. Instead of writing all this code when you haven't yet learned how to call a class method, start again with just the class and method headers. Make stubs for the headers -- the body will be only pass, or return a constant for the caller to save. Use these to get your hierarchy straight. Then restore the real method bodies. There is no need to post over 100 lines of code to illustrate a 10-line problem; I've learned to do my coding with that principle, as well.

threading tkinter add label in frame during function execution

I write a pipeline for a lab, so I know it is impossible to insert a "console" in a GUI, so I made it with a Frame and I put label on it.
But the problem is, I am a beginner in threading, and I don't know how to use it to put my label into my frame after a function execution in a loop.
So this is my code (python 3.x) :
########
# IMPORTS #
########
from tkinter import *
from tkinter import ttk
from tkinter.filedialog import *
from tkinter.messagebox import *
import os
import glob
from datetime import date, time, datetime
#########
# FUNCTION #
#########
def OneFile(path1,DB,path2,seq,seq2,typ,path3):
"""
This function is very long, take all the sequences of the input file and BLAST it to the Library DATABASE
path : path to the library databse
DB : library database name
path2 : path of the file with the query sequences
seq : name of the file with the query sequences append with a job ID
seq2 : name of the file with the query sequence
Typ : Nucleotide or Proteine
"""
from datetime import date, time, datetime
import subprocess
import platform
import time
OS = platform.system()
if OS == 'Linux' or OS == 'Darwin':
pathLibrary = path1+'/'
pathSequence = path2+'/'
pathFolder = path3+'/'
if OS == 'Windows':
pathLibrary = path1+'\\'
pathSequence = path2+'\\'
if typ not in [(1,1),(2,2),(1,2),(2,1)]:
showerror('Error : Missing Type !', "You do not choose your type\n(nucleotides or proteins)")
else:
library = DB
if os.path.isfile(pathLibrary+library) != True:
showerror('Error : Missing File !', "You must choose a Library Database file")
else:
if os.path.isfile(pathSequence+seq2) != True:
showerror('Error : Missing File !', "You must choose your sequence file")
else:
if typ == (1,1):
typ = "blastn"
if typ == (2,2):
typ = "blastp"
if typ == (1,2):
typ = "blastx"
if typ == (2,1):
typ = "tblastn"
if OS == 'Linux' or OS == 'Darwin':
t0 = time.time()
query = str(seq2)
blast = str(seq)+'_Blast.txt'
seqs = str(seq)+'_seqs.txt'
subprocess.call(typ+" -query "+pathSequence+query+" -db "+pathLibrary+library+" -evalue 1e-10 -out "+pathFolder+blast, shell=True)
subprocess.call("grep '\(Sbjct\|>\)' "+pathFolder+blast+" > "+pathFolder+seqs, shell=True)
t1 = time.time()
print('Job finish in '+str(round(t1-t0,2))+' seconds')
if OS == 'Windows':
t0 = time.time()
query = str(seq2)
blast = str(seq)+'_Blast.txt'
seqs = str(seq)+'_seqs.txt'
subprocess.call(typ+' -query '+pathSequence+query+' -db '+pathLibrary+library+' -evalue 1e-10 -out '+pathSequence+blast, shell=True)
print('Fichier n° '+str(1)+' '+str(seq2))
subprocess.Popen('findstr "Sbjct >" '+pathSequence+blast+' > '+pathSequence+seqs, shell=True)
t1 = time.time()
print('Job finish in '+str(round(t1-t0,2))+' seconds')
#######
# CLASS #
#######
class GraphicalUserInterface():
#principal application
def __init__(self):
#constructor
self.fen = Tk()
self.fen.title("Starch Enzyme Pipeline")
#first label
self.label1 = Label(self.fen, text="Folder with your set(s) : ")
self.label1.grid(row=0, columnspan=2, sticky="W")
#first button
self.browse1 = Button(self.fen)
self.browse1.config(text="Browse",command=self.folderPath)
self.browse1.grid(row=1,column=0, sticky="W")
#label to show the path
self.varLabel1 = StringVar()
self.pathLabel1 = Label(self.fen, textvariable=self.varLabel1, relief=SUNKEN)
self.pathLabel1.grid(row=1,column=1, sticky="EW")
#second title
self.label2 = Label(self.fen, text="Folder with your library database(s) ")
self.label2.grid(row=2,column = 0, columnspan=2 , sticky="W")
#second button
self.browse2 = Button(self.fen)
self.browse2.config(text="Browse",command=self.folderPath2)
self.browse2.grid(row=3,column=0, sticky="W")
#label to show the path for database
self.varLabel2 = StringVar()
self.pathLabel2 = Label(self.fen, textvariable=self.varLabel2, relief=SUNKEN)
self.pathLabel2.grid(row=3,column=1, sticky = "EW")
#Frame wrappe listBox and other
self.frameListBoxAll = Frame(self.fen)
self.frameListBoxAll.grid(row=6,columnspan=2)
#list box label
self.labListBox1 = Label(self.frameListBoxAll, text="Your sets :",padx=10)
self.labListBox1.grid(row=0,column=0)
self.labListBox2 = Label(self.frameListBoxAll, text="Your library database :",padx=10)
self.labListBox2.grid(row=0,column=1)
#frame with listbox1
self.frame1 = Frame(self.frameListBoxAll, bd=2, relief=SUNKEN)
self.frame1.grid(row=1,column=0)
#frame with listbox1
self.frame2 = Frame(self.frameListBoxAll, bd=2, relief=SUNKEN)
self.frame2.grid(row=1,column=1)
#scrollbar listbox1
self.scrollbar1 = Scrollbar(self.frame1)
self.scrollbar1.grid(row=0,column=1, sticky="NS")
self.scrollbar2 = Scrollbar(self.frame2)
self.scrollbar2.grid(row=0,column=3, sticky="NS")
self.scrollbar3 = Scrollbar(self.frame1, orient=HORIZONTAL)
self.scrollbar3.grid(row=1,column=0, sticky="WE")
self.scrollbar4 = Scrollbar(self.frame2, orient=HORIZONTAL)
self.scrollbar4.grid(row=1,column=2, sticky="WE")
#liste box
self.listeBox1 = Listbox(self.frame1, selectmode=EXTENDED, exportselection=0, yscrollcommand=self.scrollbar1.set, xscrollcommand=self.scrollbar3.set)
self.listeBox1.grid(row=0,column = 0)
self.scrollbar1.config(command=self.listeBox1.yview)
self.scrollbar3.config(command=self.listeBox1.xview)
#liste box2
self.listeBox2 = Listbox(self.frame2, selectmode=EXTENDED, exportselection=0, yscrollcommand=self.scrollbar2.set, xscrollcommand=self.scrollbar4.set)
self.listeBox2.grid(row=0,column = 2)
self.scrollbar2.config(command=self.listeBox2.yview)
self.scrollbar4.config(command=self.listeBox2.xview)
#radioboutton list box 1
self.var = IntVar()
for item in [1,2]:
if item == 1:
self.rb = Radiobutton(self.frameListBoxAll, text='Nucleotides',value=item,variable=self.var)
self.rb.grid(row=2, column=0)
if item == 2:
self.rb = Radiobutton(self.frameListBoxAll, text='Proteins',value=item,variable=self.var)
self.rb.grid(row=3, column=0)
#radioboutton list box 2
self.var2 = IntVar()
for item in [1,2]:
if item == 1:
self.rb2 = Radiobutton(self.frameListBoxAll, text='Nucleotides',value=item,variable=self.var2)
self.rb2.grid(row=2, column=1)
if item == 2:
self.rb2 = Radiobutton(self.frameListBoxAll, text='Proteins',value=item,variable=self.var2)
self.rb2.grid(row=3, column=1)
#variables
self.path1 = str()
self.path2 = str()
self.path3 = str()
#RUN Buttun
self.runbutton = Button(self.fen, text="RUN",command=self.start_foo_thread).grid(row=7,column=0,columnspan=2)
#FRAME CONSOLE
self.console = Frame(self.fen)
self.console.config(relief=SUNKEN, bg="black", height=200, width=400)
self.console.grid(row=8, columnspan=10)
self.console.grid_propagate(False) #to block the size of the frame
#QUIT BUTTON
self.quitButton = Button(self.fen)
self.quitButton.config(text="QUIT", command=self.fen.destroy)
self.quitButton.grid(row=100,column=0)
def folderPath(self):
path = askdirectory(title='Choose your set folder')
self.varLabel1.set(path)
self.listeBox1.delete(0, END)
for filename in sorted(glob.glob(path+'/*')):
if os.path.isfile(filename):
#stockage of path
self.path1 = os.path.split(filename)[0]
name = os.path.split(filename)[1]
self.listeBox1.insert(END, name)
def folderPath2(self):
path = askdirectory(title="Choose your library database folder")
self.varLabel2.set(path)
self.listeBox2.delete(0, END)
for filename in sorted(glob.glob(path+'/*')):
if os.path.isfile(filename):
#stockage of path
self.path2 = os.path.split(filename)[0]
name = os.path.split(filename)[1]
self.listeBox2.insert(END, name)
def run(self):
self.fen.mainloop()
def createJobName():
job = str(datetime.now())
job = job.replace(" ","-")
return job
def typeNP(self):
liste = []
#selection of query files
valListBox1 = [self.listeBox1.get(idx) for idx in self.listeBox1.curselection()]
#selection of database file
valListBox2 = [self.listeBox2.get(idx) for idx in self.listeBox2.curselection()]
#selection of sequence type
typ = (self.var.get(),self.var2.get())
# loop
for i in range(len(valListBox2)):
job = GraphicalUserInterface.createJobName()
path1 = self.path2
path2 = self.path1
DB = valListBox2[i]
path3 = os.getcwd()+"/"+DB+job
if os.path.isdir(DB+job) == True:
showwarning('Warning', "The folder already exist \n or they are no folder name !\nChange or get the folder name")
else:
os.mkdir(DB+job)
for filename in valListBox1:
seq = filename+job
seq2 = filename
#stock data for OneFile function
liste.append([path1,DB,path2,seq,seq2,typ,path3])
return liste
def start_foo_thread(self):
liste = self.typeNP()
for i in range(len(liste)):
global foo_thread
import threading
print('Fichier n°'+str(i+1)+' '+str(liste[i][4]))
stringLabel = Label(self.console,text='Fichier n°'+str(i+1)+' '+str(liste[i][4]),bg='black', fg='white')
stringLabel.grid(row=i,sticky="W")
foo_thread = threading.Thread(target=OneFile(liste[i][0],liste[i][1],liste[i][2],liste[i][3],liste[i][4],liste[i][5],liste[i][6]))
foo_thread.daemon = True
foo_thread.start()
#########
# AUTORUN #
#########
if __name__ == '__main__':
app = GraphicalUserInterface()
app.run()
The problem is when the loop began in:
def start_foo_thread(self):
liste = self.typeNP()
for i in range(len(liste)):
With the print function, I see the function run, but the label does not go in the frame when the iteration finishes. When the loops are completed, I see my label in the frame.
What is the correct code to have my label in my frame at the same time my function runs in my loop?
You sometimes have to manually update the widget. You have posted too much code to wade through, so this simple example should show the problem. Run as is, the labels don't show up until the function returns. Run with update_idletasks() uncommented does what I think you want. Also note that the program stops until the call to subprocess returns.
import sys
if sys.version_info[0] < 3:
import Tkinter as tk ## Python 2.x
else:
import tkinter as tk ## Python 3.x
class GraphicalUserInterface():
def __init__(self):
#constructor
self.fen = tk.Tk()
self.fen.title("Starch Enzyme Pipeline")
self.console=tk.Frame(self.fen)
self.console.grid()
self.liste=["one", "two", "three"]
tk.Button(self.fen, text="Exit", command=self.fen.quit).grid(row=1)
self.start_foo_thread()
self.fen.mainloop()
def start_foo_thread(self):
for ctr in range(len(self.liste)):
lit='Fichier n %s' % (ctr)
print(lit)
stringLabel = tk.Label(self.console, text=lit,
bg='black', fg='white')
stringLabel.grid(row=ctr,sticky="W")
##self.console.update_idletasks()
print("Waiting 2 seconds")
self.fen.after(2000) ## wait 2 seconds to show effect
print("Return from function")
if __name__ == '__main__':
app = GraphicalUserInterface()

How to make ttk.Treeview's rows editable?

Is there any way to use ttk Treeview with editable rows?
I mean it should work more like a table. For example on double click on the item make the #0 column 'editable'.
If this isn't possible, any way to allow mouse selecting on the item would be just fine. I haven't found any mention of this in tkdocs or other documents.
After long research I haven't found such feature so I guess there's any. Tk is very simple interface, which allows programmer to build 'high-level' features from the basics. So my desired behaviour this way.
def onDoubleClick(self, event):
''' Executed, when a row is double-clicked. Opens
read-only EntryPopup above the item's column, so it is possible
to select text '''
# close previous popups
# self.destroyPopups()
# what row and column was clicked on
rowid = self._tree.identify_row(event.y)
column = self._tree.identify_column(event.x)
# get column position info
x,y,width,height = self._tree.bbox(rowid, column)
# y-axis offset
# pady = height // 2
pady = 0
# place Entry popup properly
text = self._tree.item(rowid, 'text')
self.entryPopup = EntryPopup(self._tree, rowid, text)
self.entryPopup.place( x=0, y=y+pady, anchor=W, relwidth=1)
This is method within a class which composes ttk.Treeview as self._tree
And EntryPopup is then very simple sub-class of Entry:
class EntryPopup(Entry):
def __init__(self, parent, iid, text, **kw):
''' If relwidth is set, then width is ignored '''
super().__init__(parent, **kw)
self.tv = parent
self.iid = iid
self.insert(0, text)
# self['state'] = 'readonly'
# self['readonlybackground'] = 'white'
# self['selectbackground'] = '#1BA1E2'
self['exportselection'] = False
self.focus_force()
self.bind("<Return>", self.on_return)
self.bind("<Control-a>", self.select_all)
self.bind("<Escape>", lambda *ignore: self.destroy())
def on_return(self, event):
self.tv.item(self.iid, text=self.get())
self.destroy()
def select_all(self, *ignore):
''' Set selection on the whole text '''
self.selection_range(0, 'end')
# returns 'break' to interrupt default key-bindings
return 'break'
You could also pop up a tool window with the editable fields listed with Entries to update the values. This example has a treeview with three columns, and does not use subclasses.
Bind your double click to this:
def OnDoubleClick(self, treeView):
# First check if a blank space was selected
entryIndex = treeView.focus()
if '' == entryIndex: return
# Set up window
win = Toplevel()
win.title("Edit Entry")
win.attributes("-toolwindow", True)
####
# Set up the window's other attributes and geometry
####
# Grab the entry's values
for child in treeView.get_children():
if child == entryIndex:
values = treeView.item(child)["values"]
break
col1Lbl = Label(win, text = "Value 1: ")
col1Ent = Entry(win)
col1Ent.insert(0, values[0]) # Default is column 1's current value
col1Lbl.grid(row = 0, column = 0)
col1Ent.grid(row = 0, column = 1)
col2Lbl = Label(win, text = "Value 2: ")
col2Ent = Entry(win)
col2Ent.insert(0, values[1]) # Default is column 2's current value
col2Lbl.grid(row = 0, column = 2)
col2Ent.grid(row = 0, column = 3)
col3Lbl = Label(win, text = "Value 3: ")
col3Ent = Entry(win)
col3Ent.insert(0, values[2]) # Default is column 3's current value
col3Lbl.grid(row = 0, column = 4)
col3Ent.grid(row = 0, column = 5)
def UpdateThenDestroy():
if ConfirmEntry(treeView, col1Ent.get(), col2Ent.get(), col3Ent.get()):
win.destroy()
okButt = Button(win, text = "Ok")
okButt.bind("<Button-1>", lambda e: UpdateThenDestroy())
okButt.grid(row = 1, column = 4)
canButt = Button(win, text = "Cancel")
canButt.bind("<Button-1>", lambda c: win.destroy())
canButt.grid(row = 1, column = 5)
Then confirm the changes:
def ConfirmEntry(self, treeView, entry1, entry2, entry3):
####
# Whatever validation you need
####
# Grab the current index in the tree
currInd = treeView.index(treeView.focus())
# Remove it from the tree
DeleteCurrentEntry(treeView)
# Put it back in with the upated values
treeView.insert('', currInd, values = (entry1, entry2, entry3))
return True
Here's how to delete an entry:
def DeleteCurrentEntry(self, treeView):
curr = treeView.focus()
if '' == curr: return
treeView.delete(curr)
I have tried #dakov solution but it did not work for me since my treeView has multiple columns and for few more reasons. I made some changes that enhanced it so here is my version
class Tableview(ttk.Treeview):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
tv.bind("<Double-1>", lambda event: self.onDoubleClick(event))
def onDoubleClick(self, event):
''' Executed, when a row is double-clicked. Opens
read-only EntryPopup above the item's column, so it is possible
to select text '''
# close previous popups
try: # in case there was no previous popup
self.entryPopup.destroy()
except AttributeError:
pass
# what row and column was clicked on
rowid = self.identify_row(event.y)
column = self.identify_column(event.x)
# handle exception when header is double click
if not rowid:
return
# get column position info
x,y,width,height = self.bbox(rowid, column)
# y-axis offset
pady = height // 2
# place Entry popup properly
text = self.item(rowid, 'values')[int(column[1:])-1]
self.entryPopup = EntryPopup(self, rowid, int(column[1:])-1, text)
self.entryPopup.place(x=x, y=y+pady, width=width, height=height, anchor='w')
The EntryPopup class
class EntryPopup(ttk.Entry):
def __init__(self, parent, iid, column, text, **kw):
ttk.Style().configure('pad.TEntry', padding='1 1 1 1')
super().__init__(parent, style='pad.TEntry', **kw)
self.tv = parent
self.iid = iid
self.column = column
self.insert(0, text)
# self['state'] = 'readonly'
# self['readonlybackground'] = 'white'
# self['selectbackground'] = '#1BA1E2'
self['exportselection'] = False
self.focus_force()
self.select_all()
self.bind("<Return>", self.on_return)
self.bind("<Control-a>", self.select_all)
self.bind("<Escape>", lambda *ignore: self.destroy())
def on_return(self, event):
rowid = self.tv.focus()
vals = self.tv.item(rowid, 'values')
vals = list(vals)
vals[self.column] = self.get()
self.tv.item(rowid, values=vals)
self.destroy()
def select_all(self, *ignore):
''' Set selection on the whole text '''
self.selection_range(0, 'end')
# returns 'break' to interrupt default key-bindings
return 'break'
from tkinter import ttk
from tkinter import *
root = Tk()
columns = ("Items", "Values")
Treeview = ttk.Treeview(root, height=18, show="headings", columns=columns) #
Treeview.column("Items", width=200, anchor='center')
Treeview.column("Values", width=200, anchor='center')
Treeview.heading("Items", text="Items")
Treeview.heading("Values", text="Values")
Treeview.pack(side=LEFT, fill=BOTH)
name = ['Item1', 'Item2', 'Item3']
ipcode = ['10', '25', '163']
for i in range(min(len(name), len(ipcode))):
Treeview.insert('', i, values=(name[i], ipcode[i]))
def treeview_sort_column(tv, col, reverse):
l = [(tv.set(k, col), k) for k in tv.get_children('')]
l.sort(reverse=reverse)
for index, (val, k) in enumerate(l):
tv.move(k, '', index)
tv.heading(col, command=lambda: treeview_sort_column(tv, col, not reverse))
def set_cell_value(event):
for item in Treeview.selection():
item_text = Treeview.item(item, "values")
column = Treeview.identify_column(event.x)
row = Treeview.identify_row(event.y)
cn = int(str(column).replace('#', ''))
rn = int(str(row).replace('I', ''))
entryedit = Text(root, width=10 + (cn - 1) * 16, height=1)
entryedit.place(x=16 + (cn - 1) * 130, y=6 + rn * 20)
def saveedit():
Treeview.set(item, column=column, value=entryedit.get(0.0, "end"))
entryedit.destroy()
okb.destroy()
okb = ttk.Button(root, text='OK', width=4, command=saveedit)
okb.place(x=90 + (cn - 1) * 242, y=2 + rn * 20)
def newrow():
name.append('to be named')
ipcode.append('value')
Treeview.insert('', len(name) - 1, values=(name[len(name) - 1], ipcode[len(name) - 1]))
Treeview.update()
newb.place(x=120, y=(len(name) - 1) * 20 + 45)
newb.update()
Treeview.bind('<Double-1>', set_cell_value)
newb = ttk.Button(root, text='new item', width=20, command=newrow)
newb.place(x=120, y=(len(name) - 1) * 20 + 45)
for col in columns:
Treeview.heading(col, text=col, command=lambda _col=col: treeview_sort_column(Treeview, _col, False))
root.mainloop()
After so much research while doing my project got this code, it helped me a lot.
Double click on the element you want to edit, make the required change and click 'OK' button
I think this is what exactly you wanted
#python #tkinter #treeview #editablerow
New row
Editable row
This is just for creating a tree for the specified path that is set in the constructor. you can bind your event to your item on that tree. The event function is left in a way that the item could be used in many ways. In this case, it will show the name of the item when double clicked on it. Hope this helps somebody.
import ttk
from Tkinter import*
import os*
class Tree(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
path = "/home/...."
self.initUI(path)
def initUI(self, path):
self.parent.title("Tree")
self.tree = ttk.Treeview(self.parent)
self.tree.bind("<Double-1>", self.itemEvent)
yScr = ttk.Scrollbar(self.tree, orient = "vertical", command = self.tree.yview)
xScr = ttk.Scrollbar(self.tree, orient = "horizontal", command = self.tree.xview)
self.tree.configure(yscroll = yScr.set, xScroll = xScr.set)
self.tree.heading("#0", text = "My Tree", anchor = 'w')
yScr.pack(side = RIGHT, fill = Y)
pathy = os.path.abspath(path)
rootNode = self.tree.insert('', 'end', text = pathy, open = True)
self.createTree(rootNode, pathy)
self.tree.pack(side = LEFT, fill = BOTH, expand = 1, padx = 2, pady = 2)
self.pack(fill= BOTH, expand = 1)
def createTree(self, parent, path)
for p in os.listdir(path)
pathy = os.path.join(path, p)
isdir = os.path.isdir(pathy)
oid = self.tree.insert(parent, 'end' text = p, open = False)
if isdir:
self.createTree(oid, pathy)
def itemEvent(self, event):
item = self.tree.selection()[0] # now you got the item on that tree
print "you clicked on", self.tree.item(item,"text")
def main():
root = Tk.Tk()
app = Tree(root)
root.mainloop()
if __name__ == '__main__'
main()
You should not do this manually
there are ready to use pack that have this Feature and many more such as
tkintertable
it have some insane features
there is also pygubu-editable-treeview
if you are intrested in pygubu,
as for the the reason you shouldnt code your own ,
in order to do a good treeview you will need to build more Feature that make your gui easier to use
however such Feature takes hundred lines of code to create.(takes a long time to get right)
unless you are making a custom TREE-View-widget,it doesnot worth the effort.
I don't know about making the row editable, but to capture clicking on a row, you use the <<TreeviewSelect>> virtual event. This gets bound to a routine with the bind() method, then you use the selection() method to get the ids of the items selected.
These are snippets from an existing program, but show the basic sequence of calls:
# in Treeview setup routine
self.tview.tree.bind("<<TreeviewSelect>>", self.TableItemClick)
# in TableItemClick()
selitems = self.tview.tree.selection()
if selitems:
selitem = selitems[0]
text = self.tview.tree.item(selitem, "text") # get value in col #0

I can't figure out this Tkinter error

I'm using Python's Tkinter to create a GUI for a project i'm working on.
When I try to run part of the code though, I get this error:
Traceback (most recent call last):
File "calculator.py", line 59, in <module>
app = Application()
File "calculator.py", line 28, in __init__
self.create_widgets()
File "calculator.py", line 45, in create_widgets
self.special_chars.create_button(char, self.add_char_event(special_characters[char]))
File "calculator.py", line 20, in create_button
self.button_list += Button(self, text = txt, command = fcn)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/
lib-tk/Tkinter.py", line 1206, in cget
TypeError: cannot concatenate 'str' and 'int' objects
The problem is that I can't find the file that the error message references; my python2.7/lib-tk folder only contains complied versions (.pyo and .pyc) of Tkinter.
Is there a way to figure out what's going wrong?
Here's the source of calculator.py
from Tkinter import *
from exp import full_eval
from maths import special_characters
class special_char_frame(LabelFrame):
def __init__(self, master = None, text = 'Special Characters'):
LabelFrame.__init__(self, master)
self.grid()
self.button_list = []
def create_button(self, txt, fcn):
self.button_list += Button(self, text = txt, command = fcn)
self.button_list[-1].grid(row = 0)
class Application(Frame):
def __init__(self, master = None):
Frame.__init__(self, master)
self.grid()
self.create_widgets()
def create_widgets(self):
## equation entry pane
self.text_entry = Entry(self, width = 100)
self.text_entry.grid(row = 0, column = 0)
self.text_entry.bind('<KeyPress-Return>', self.calculate)
## result pane
self.result = StringVar()
self.result_label = Label(self, textvariable = self.result, wraplength = 815, justify = LEFT)
self.result_label.grid(row = 1, column = 0, columnspan = 2, sticky = W)
self.result.set('')
## calculate button
self.calc_button = Button(self, text = 'Calculate', command = self.calculate)
self.calc_button.grid(row = 0, column = 1)
## special character button pane
self.special_chars = special_char_frame(self)
for char in special_characters:
self.special_chars.create_button(char, self.add_char_event(special_characters[char]))
self.special_chars.grid(column = 0, columnspan = 2, row = 2)
def calculate(self, event = None):
try:
self.result.set(full_eval(self.text_entry.get()))
except Exception as error:
raise
#self.result.set(str(error))
self.text_entry.select_range(0, END)
def add_char_event(self, char):
def add_char(self = self, event = None):
self.text_entry.insert(INSERT, char)
return add_char
app = Application()
app.master.title('Calculator')
app.mainloop()
full_eval is a function for evaluating mathematical expressions.
special_characters is a dict containing special characters and their explanations. For now it's just special_characters = {'imaginary unit' : u'\u2148'}
Ok, so I missed this the first time, but the issue is actually that you are trying to add a Button to a list:
self.button_list += Button(self, text = txt, command = fcn)
If you simply wrap the Button in brackets, the error goes away (which makes sense because you are supposed to be able to add two lists):
self.button_list += [Button(self, text = txt, command = fcn)]
ORIGINAL ATTEMPT
My guess:
special_characters is a dictionary. It has key-value mappings where the values are ints. Then, when used in self.text_entry.insert(INSERT, char), text_entry is trying to insert an int into a str and causing the above error. The simple solution: wrap char with str in add_char.
def add_char_event(self, char):
def add_char(self = self, event = None):
self.text_entry.insert(INSERT, str(char))
return add_char
Your other option is to wrap str around the special_characters lookup:
for char in special_characters:
self.special_chars.create_button(char,
self.add_char_event(str(special_characters[char])))

Categories

Resources