delete item from listbox on tkinter - python

I am trying to delete item from listbox. i am using python2.7. when i am using remove it shows error.the same is for delete also
import tkinter
window=Tk()
ncbox = Tkinter.Listbox(window, width=14, height=7,fg="blue",font=("Helvetica", 20))
ncbox.grid(row=2, column=2,columnspan=4,sticky=NW)
yscroll = Tkinter.Scrollbar(command=ncbox.yview, orient=Tkinter.VERTICAL)
yscroll.grid(row=2, column=4, sticky=Tkinter.N+Tkinter.S)
ncbox.configure(yscrollcommand=yscroll.set)
msg1='abc'
msg2='xyz'
gap=' '
ncbox.insert(Tkinter.END, msg1+gap+msg2)
ncbox.delete(msg1+gap+msg2)
if msg3+gap+msg4 in ncbox:
print 'found'
window.mainloop()
How i could delete data? when i want to search it says that in is not a command for listbox. how could i change the color of every inserted text?

The error is telling you exactly what the problem is: you are giving it a bad index. The documentation for the delete method says you have to give an index. The documentation for the listbox widget describes what is a valid index -- a number, and a few special strings.
You need to tell the delete method which item number you want to delete.

Related

How to create a function to delete a character in a label tkinter python?

I'm about to finish a calculator in tkinter python. One of the last things I need to do is create a button which will delete one character at a time from the label. I've already created a button which will clear everything, but there all I did was var.set(" ") to essentially replace everything with a space. I'm not sure how to make a function which will delete 1 character at a time which is what I need to do.
This is the code for the button so far. I tried inserting a backspace but realised that wouldn't work.
delete = Button(e, text = "C",width=4, command = lambda: insert("\b"), font = "Helvetica 50",highlightbackground='#737373')
delete.place(x = 228, y = 301)
Any help on how to create a function like this is appreciated.
A quick way would be to say:
delete = Button(..., command=lambda: var.set(var.get()[:-1]), ...)
A lengthier way would be to create a descriptive function and remove the use of StringVar:
def func():
text = label.cget('text')[:-1] # Get the text of the label and slice till the last letter
label.config(text=text) # Set the text of label to the new text
delete = Button(..., command=func, ...)

TKINTER: I can't copy a string output

I created a simple GUI application that returns a string after taking a user input. I want to be able to copy the string once it's printed on the GUI but I can't, I think it's because initally I used Label:
d = 'some string that I want to copy'
data = Label(main, text=d)
data.pack()
I tried doing Text instead so that I can copy the output from a text box but I keep getting this error message:
bad wrap "some string that I want to copy" must be char, none, or word.
code:
data = Text(main, wrap=d)
data.pack()
The wrap option takes one of the following three strings: word, none, or char. You're passing something else.
If your goal is to insert the value of d in a text widget, you must use the insert method after creating the widget:
data = Text(main, wrap="word")
data.insert("end", d)
This works?
from tkinter import *
main = Tk()
d='This is the input'
data = Label(main, text=d)
data.pack()
main.mainloop()
All though it would help if you posted your full code

How to move the insertion cursor of a tkinter text widget to a certain index

I want to move the insertion cursor(caret)(|) within the tkinter text widget, to a certain text widget indice.
USE CASE:
I am making an autocomplete program wherein if I type one single apostrophe(quotation mark), the other one automatically is inserted into the text widget, which I got working all fine. But after, the second apostrophe is generated I want to bring the insertion cursor(caret), in the middle of the two apostrophes rather than at the end. Like so -:
One apostrophe typed(inside the tkinter text widget) -:
'[insertion cursor(caret)(|)]
The other one is auto-inserted pushing the insertion cursor(caret) to the end(The code till this part has been figured out by me successfully.) -:
''[insertion cursor(caret)(|)]
The insertion cursor(caret) shifts between the two apostrophes(The objective of this question.) -:
'[insertion cursor(caret)(|)]'
NOTE: These operations are all taking place within a tkinter text widget.
You call the mark_set method, using "insert" as the name of the mark.
the_widget.mark_set("insert", "4.0") will set the insertion cursor at the start of the fourth line. You can use the_widget.mark_set("insert", "insert-1c") to move the cursor back one character.
Here is an example of one way for automatically inserting a closing parenthesis or bracket. In this example, the code inserts both the opening and closing character so it returns "break" to prevent the default behavior provided by the text widget.
import tkinter as tk
def autocomplete(widget, first, last):
# insert the two characters at the insertion point
widget.insert("insert", first + last)
# move insertion cursor back one character
widget.mark_set("insert", "insert-1c")
# prevent the text widget from inserting the character that
# triggered the event since we've already inserted it.
return "break"
root = tk.Tk()
text = tk.Text(root, wrap="word")
text.pack(fill="both", expand=True)
text.bind("(", lambda event: autocomplete(event.widget, "(", ")"))
text.bind("[", lambda event: autocomplete(event.widget, "[", "]"))
root.mainloop()

Formatting text while typing in a Tkinter Text widget

I'm trying to add notes to a given text that's not to be altered. It's pretty much like formatting in common text editors.
I have tried to get the current cursor position via .index('insert'), and then tag the character either forwards with tag_add(current cursor, current cursor '+1c'), or backwards with tag_add(current cursor + '-1c', current cursor). This results in tagging either the character right before or after the character just typed.
Are there any workarounds to live-tag the actually typed character?
import tkinter
main = tkinter.Tk()
def typing(event):
text.tag_configure('note', background='yellow')
text.tag_configure('note2', background='blue')
cur_cursor = text.index("insert")
text.tag_add('note', cur_cursor + '-1c', cur_cursor)
text.tag_add('note2', cur_cursor, cur_cursor + '+1c')
text = tkinter.Text(main)
text.grid()
text.bind('<Key>', typing)
for i in ['OX'*20 + '\n' for i in range(10)]:
text.insert('end', i)
main.mainloop()
Edit: Although Bryan's answer worked for me you might get problems with fast typing as described here: how-to-get-cursor-position
The simplest solution is to bind on <KeyRelease> rather than <Key>. The reason is that the text widget doesn't actually insert the character you typed until its own <Key> binding fires, and that binding always fires after any custom bindings you have on the widget.

Finding the currently selected tab of Ttk Notebook

I have a Ttk Notebook widget containing 8 Frames - so, 8 tabs. Each frame contains a Text widget. I have a button outside the Notebook widget, and I want to insert text into the current tabs Text widget when this button is pressed.
This would seem to require working out which widget in the Notebook is currently selected, but I can't seem to find how to do this. How would I find the currently selected tab?
Alternatively, how can I implement what I want to?
If it helps, here's the code for my notebook:
self.nb = Notebook(master)
self.nb.pack(fill='both', expand='yes', padx=10, pady=10)
self.frames = []
self.texts = []
for i in xrange(8):
self.frames.append(Frame())
self.nb.add(self.frames[i])
self.texts.append(Text(self.frames[i]))
self.texts[i].pack(fill='both')
You can retrieve the selected tab through select method. However, this method returns a tab_id which is not much useful as is. index convert it to the number of the selected tab.
>>> nb.select()
'.4299842480.4300630784'
>>> nb.index(nb.select())
2
Note that you coud also get more information about the selected tab using tab
>>> nb.tab(nb.select(), "text")
'mytab2'
You might look at Notebook reference documentation : http://docs.python.org/3/library/tkinter.ttk.html#notebook
You can get currently selected tab using the "current" keyword:
noteBook.index("current")
Check this website:
https://docs.python.org/2/library/ttk.html#tab-identifiers
24.2.5.3. Tab Identifiers
There are two simple ways to see which tab is selected:
nb.select() # returns the Tab NAME (string) of the current selection
and
nb.index('current') # returns the Tab INDEX (number) of the current selection
The .select() method can also be used to select which tab is currently active, via nb.select(tabId). Without the arg, it returns the tabId (in "name" form) of the current selection.
The .index(tabId) converts a tabId into a numerical index. It also can take the string "end" which will return the number of tabs. So, nb.index(tkinter.END) is like a len() method for a notebook widget.
When there are no tabs, .select() returns an empty string, but .index('current') throws an exception. So, if you want the index, I would say
if nb.select():
idx = nb.index('current')
is the best way to go.
In your particular case, you would probably want to grab the current notebook tab name and then convert that name into the actual child text widget, via the nametowidget() method, for manipulation. So...
tabName = notebook.select()
if tabName:
textWidget = notebook.nametowidget(tabName) # here, 'notebook' could be any widget
textWidget.insert(pos, text, tags)
The nametowidget(name) method maps a Tkinter name to the actual widget. It is a method callable by any actual widget.
I am not a expert at all but hope i can help with some "fresh eyes".
I imagine it could be something involving
def buttonclick():
somevariablename = focus_get()
#Print your text into the somevariable notebook could be
#something like(not sure about the syntax):
focusednotebook = somevariablename
focusednotebook.insert('1.0', 'your text here')
yourbutton = Button(parent, text = "button name", command = buttonclick)
yourbutton.pack()
Hope it works or get you in the right direction.
Please feel free to edit as I am fairly new here amd with python :-)
Getting the tageted tab in tk.Notebook it's easy all you have to do is to use the notebook object and target the index of the current tab. This can be done as follows
# creating a notebook object
notebook = ttk.Notebook(root, height=height, width=width, padding=20)
# Adding tabs
notebook.add(bin_tab, text="Binary Conversion")
notebook.add(oct_tab, text="Octal Conversion")
notebook.add(hex_tab, text="Hexadecimal Conversion")
print(notebook.index("current")) # returns 0, 1, 2depending on how many tabs you have in my case i have 3 which means index from 0 to 2

Categories