Finding the currently selected tab of Ttk Notebook - python

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

Related

QLineEdit dont want to save changes :(

stackoverflow!
It's my first question, I was just a reader before
I'm trying to make an app in python using PyQt5: I need to get data from DB into a table, every row has an EDIT button, when you push it, fields of the row become editable and you can change the data and the EDIT button changes to SAVE button. When you push it , data should be saved and be sent to database(I didn't made a "commit to DB" function yet) but its not saving and comes to previous amounts every time I click SAVE.
When I click EDIT button, it takes a cell text and than replace the widget in a cell by the same , but editable version(just change an option to EDITABLE = TRUE is not working), and it makes it for the whole row.
The save button should make the same, but it makes cells UNEDITABLE again...
tell me why it is so?
my function on SAVE button is
def ButtonSaveClicked(self):
s = self.sender()
roww = int((s.text().split())[1]) - 1
print('SAVE')
# replacing the existing active widgets by inactive with a same text
q = self.ui.tableWidget.item(roww, 0).text()
self.ui.btn_sell = QtWidgets.QLineEdit(q)
self.ui.btn_sell.setEnabled(False)
self.ui.tableWidget.setCellWidget(roww, 0, self.ui.btn_sell)
q = self.ui.tableWidget.item(roww, 1).text()
print(q)
self.ui.btn_sell = QtWidgets.QLineEdit(q)
self.ui.btn_sell.setEnabled(False)
self.ui.tableWidget.setCellWidget(roww, 1, self.ui.btn_sell)
q = self.ui.tableWidget.item(roww, 2).text()
print(q)
self.ui.btn_sell = QtWidgets.QLineEdit(q)
self.ui.btn_sell.setEnabled(False)
self.ui.tableWidget.setCellWidget(roww, 2, self.ui.btn_sell)
self.ui.btn_sell = QtWidgets.QPushButton("Edit " +str(roww+1))
self.ui.btn_sell.setEnabled(True)
self.ui.tableWidget.setCellWidget(roww, 3, self.ui.btn_sell)
self.ui.btn_sell.clicked.connect(self.ButtonEditClicked)
enter image description here
I will attempt to answer your question, but I think you may also want to consider the following alternative:
You can set your table to have Edit Triggers instead of you needing to keep track of the state of a QPushButton and keep replacing items and copying data back and forth between them.
My suggestion would be to use the QAbstractItemView::DoubleClicked edit trigger and you can apply that to your QTableWidget like this:
self.tableWidget.setSelectionBehavior(QAbstractItemView::SelectItems)
self.tableWidget.setSelectionMode(QAbstractItemView::SingleSelection)
self.tableWidget.setEditTriggers(QAbstractItemView::DoubleClicked)
If the user double clicks on a cell, that cell becomes editable.
setSelectionBehavior() lets you choose whether you want each cell, row or column to be selected when clicked.
setSelectionMode() determines whether one (cell,row,column) or many (cells,rows,columns) can be selected at once. I think in your case you want to select one cell at a time.
This way the user can double click the cells they wish to edit and then you can have a "Save" button at the bottom of the widget which saves all the changes.
I will try to reproduce your problem above, but I wanted to bring this functionality to your attention as it may save you a lot of headaches.

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, ...)

Python Text Widget - Displays Nothing on GUI

I am trying to populate 2 columns from my heap list into a text widget on my GUI. I have included my code below which does the same. self.top5 is my list which displays the first 5 elements sorted in descending order
self.tableSize = 25
self.hashTable = [[] for i in range(25)]
self.top5 = [(0,0) * 5]
After creating heap,validating hashkey,appending etc
self.top5 = (heapq.nlargest(5,heap)
self.text.tag_configure('big',foreground = '#5C0000',font('Verdana',9,'bold'))
self.text.tag_configure('sub',foreground = '#000000',font('Verdana',9,'bold'))
self.text.tag_configure('val',foreground = '#000000',font =('Verdana',9))
self.text.insert(INSERT,"\nEMP STATISTICS:",'big')
self.text.insert(END,"\n")
self.text.insert(INSERT,"EMP NUMBER:",'sub')
self.text.insert(END,"\t")
self.text.insert(INSERT,self.eID,'val')
self.text.insert(END,",")
self.text.insert(INSERT,"EMP NAME:",'sub')
self.text.insert(END,"\t")
self.text.insert(INSERT,self.eName,'val')
self.text.insert(END,",")
for k in self.top5:
self.text.insert(INSERT,k[0],'val')
self.text.insert(END, "\t\t")
self.text.insert(INSERT,k[1],'val')
self.text.insert(END,"\t\t\t")`
When i run my program, somehow nothing comes up on my screen. Though there is no error. Also, I am inserting first into my heapq and then fetching the top5 details sorted using nlargest.
Can someone please explain why am I not able to see any data on my GUI? When I use print statements at certain checkpoints, it works and I can definitely see proper output on terminal. I am a newbie, pardon me if it's too silly/obvious.
I'm pretty sure in order to display a GUI you need:
root = tkinter.Tk()
root.title("YOUR TITLE HERE")
And then you need to use pack() after whatever you want to be displayed on the GUI and once that's done you need root.mainloop() to display the GUI altogether.

How can I set the text widget contents to the value of a variable in Python/Tkinter?

I am writing a program to assist with a trivial part of my job that can be automated. My purpose here is to:
Copy and paste a chunk of plain text into a Tkinter text widget
Use that pasted chunk of text as the value of a variable so that the variable can have certain characters pulled and returned down the line.
I have a functioning little bit of code. For example, here is my text widget and the lines of code I use to get and print its contents:
textBox = Text(root)
textBox.focus_set()
def get_input():
print textBox.get(1.0, 'end-1c')
Then I use a button that uses the command get_input. It works when it comes to printing the contents of the widget.
Now that I know how to properly call on the contents and 'get' them, I would like to learn how I can assign those contents (a string) to the value of a variable.
I think what you want is this. It will delete all the text and then insert a variable.
def set_input(value):
text.delete(1.0, "END")
text.insert("END", value)
It is Python 2.x only. Python 3 requires that "END" be END from the Tk namespace.
def set_value():
text.insert("end-1c", value)

delete item from listbox on tkinter

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.

Categories