I cant print the key value of the dic when I print the value of each list
I tried with the code I wrote down!
import tkinter as tk
from tkinter import ttk
limit_before_list = [0]
max_posts_list = [0]
max_comments_list = [0]
limit_before = 'limit_before'
max_posts = 'max_posts'
max_comments = 'max_comments'
def mostrar_nombre(event):
listbox = event.widget
index = listbox.curselection()
value = listbox.get(index[0])
print(pestaña_text)
print(value)
pestañas = {
limit_before: list(range(0, 160, 10)),
max_posts: list(range(0, 410, 10)),
max_comments: list(range(0, 4100, 100)),
}
note = ttk.Notebook()
for pestaña, items in pestañas.items():
frame = ttk.Frame(note)
note.add(frame, text=pestaña)
listbox = tk.Listbox(frame, exportselection=False)
listbox.grid(row=0, column=0)
listbox.bind("<<ListboxSelect>>", mostrar_nombre)
if pestaña == limit_before:
pestaña_text = limit_before
elif pestaña == max_posts:
pestaña_text = max_posts
elif pestaña == max_comments:
pestaña_text = max_comments
for item in items:
listbox.insert(tk.END, item)
note.pack()
note.mainloop()
I excpected something like with the prints. The problem is when I print, I have the same Key for all listbox
>>>limit_before
>>>50
>>>max_post
>>>60
>>>max_comments
>>>100
>>>max_post
>>>30
....
Creating the variable pestaña_text is not handy in this case. It is defined in the main scope but it is overridden in the for loop and keeps the last value max_comments:
for pestaña, items in pestañas.items():
...
if pestaña == limit_before:
pestaña_text = limit_before
elif pestaña == max_posts:
pestaña_text = max_posts
elif pestaña == max_comments:
pestaña_text = max_comments
So when you call it next, in the the function mostrar_nombre, you will only get max_comments.
You can delete this for loop and use directly the selected tab text attribute by referring to the active tab of the NoteBook object with the method select:
def mostrar_nombre(event):
listbox = event.widget
index = listbox.curselection()
value = listbox.get(index[0])
print(note.tab(note.select(), "text"))
print(value)
Some doc here and another similar question here.
Related
I'm having a problem on how can I remove an item from the list widget using a button and possibly how can I clear the widget after checking all the item.
py.file
class MenuScreen(Screen):
def add_item(self):
global lst
i = 0
if self.ids.inp.text == "":
close_button = MDFlatButton(text="Okay", on_release=self.close_dialog)
self.dialog = MDDialog(title="Invalid", text="No item added",
size_hint=(0.7, 1), buttons=[close_button])
self.dialog.open()
else:
list_items.append(self.ids.inp.text)
self.ids.inp.text = ''
for x in range(len(list_items)):
lst = OneLineAvatarIconListItem(text=list_items[i])
i += 1
self.ids.list.add_widget(lst)
def close_dialog(self, obj):
self.dialog.dismiss()
def remove_item(self):
pass
Example image:
For removing the item that is selected you can use self.ids.list.children to access all the items in your list and simply use remove_widget() to remove that item.And to clear your list after all the items are selected,you can use clear_widgets().
A part of my selection menu is a 'recents' menu, consisting of the 5 most recently selected menuitems. So whenever the user selects an item from the menu, it should update this part of the menu.
In order to do this, I need to replace those menu items with new ones. But apparently just keeping a reference to them and pointing it at a new object is not enough. The menu is not rebuilt on the fly.
Code:
def rebuild_recents_menu(self):
counter = 0
for item in self._build_recents_menu():
self.recent_group['base_group'][counter] = item
counter += 1
GLib.idle_add(self.asset_menu.show_all) # self.assets_menu is a reference to the menu to which the submenu is attached
def _build_recents_menu(self):
recent_group = {
'base_group': [],
'subgroup_quotes': [],
'subgroup_exchanges': []
}
for i in range(0,5):
if i > len(self.coin.settings.get('recent'))-1:
base_item = self.create_base_item(None, recent_group, hidden = True)
else:
base = self.coin.settings.get('recent')[i]
base_item = self.create_base_item(base, recent_group)
yield base_item
self.recent_group = recent_group
def create_base_item(self, base, group, hidden = False):
if hidden:
base_item = Gtk.RadioMenuItem.new_with_label(group.get('base_group'), 'hidden')
base_item.hide()
else:
base_item = Gtk.RadioMenuItem.new_with_label(group.get('base_group'), base)
base_item.set_submenu(self._menu_quotes(base, group.get('subgroup_quotes'), group.get('subgroup_exchanges')))
group.get('base_group').append(base_item)
if self.exchange.asset_pair.get('base') == base:
base_item.set_active(True)
base_item.connect('toggled', self._handle_toggle, base)
return base_item
I am puzzled.
I have written this little piece of code before and used it somewhere else:
def testBut(p):
print(root)
for items in root.findall("a/item"):
print(items.get("name"))
and it has worked just fine.
But now in my newer project i have the following code:
for items in root.findall("a/item"):
print(items.get("name"))
def testBut(p):
print(root)
for items in root.findall("a/item"):
print(items.get("name"))
so OUTSIDE the def. it workes just fine, and shows me all the items in a, where as INSIDE the def i get nothing but root (because i print it). Can anyone explain why?
i am sorry if this is a repost or whatever, but i simply cannot find an answer, especially given it works just fine in a different file but exact same setup..
edit: full(ish) code.
from tkinter import *
from xml.etree.ElementTree import ElementTree
from xml.etree.ElementTree import Element
import xml.etree.ElementTree as ET
tree = ET.parse("Alphabet.xml")
root = tree.getroot()
colour0 = "WHITE"
colour1 = "OLIVEDRAB1"
colour2 = "PALETURQUOISE1"
colour3 = "ROSYBROWN1"
font1 = "Arial, 24"
counterRow = 1
counterColumn = 0
for items in root.findall("a/item"):
print(items.get("name"))
def testBut(p):
print(root)
for items in root.findall("a/item"):
print("test")
print(items.get("name"))
def setup():
for letters in root:
global counterRow
global counterColumn
letters.tag = Button(vindue, text=letters.tag, font=font1,
command=lambda p=letters.tag: testBut(p))\
.grid(row=counterRow, column=counterColumn, sticky="nsew")
counterColumn += 1
if counterColumn > 7:
counterRow += 1
counterColumn = 0
def reset():
for buttons in vindue.grid_slaves():
if buttons.grid_info()["row"] > 0:
buttons.grid_forget()
def showBut(input):
counter = 0
reset()
lst = []
print(input)
str = input+"/item"
print(str)
for items in root.findall("a/item"):
print(items.get("name"))
print("test")
varstr = items.get("name")+"Var"
varstr = IntVar()
varstr2 = items.get("name")
varstr2 = Button(vindue, text=items.get("name"), font="Arial, 44", command=lambda varstr=varstr: (varstr.set(varstr.get() + 1), print(varstr.get())))
varstr2.grid(row=1, column=counter)
counter += 1
vindue = Tk()
setup()
vindue.mainloop()
I am working on an Autocomplete text editor. It take an input from the user when space is pressed and prints the list of words with prefix mentioned by the user.
Here is the code:
#!/usr/bin/env python
from tkinter import *
import tkinter.font as tkFont
class Node:
def __init__(self):
self.word = None
self.nodes = {} # dict of nodes
def __get_all__(self):
x = []
for key, node in self.nodes.items():
if (node.word is not None):
x.append(node.word)
x = x + node.__get_all__
return x
def __str__(self):
return self.word
def __insert__(self, word, string_pos=0):
current_letter = word[string_pos]
if current_letter not in self.nodes:
self.nodes[current_letter] = Node();
if (string_pos + 1 == len(word)):
self.nodes[current_letter].word = word
else:
self.nodes[current_letter].__insert__(word, string_pos + 1)
return True
def __get_all_with_prefix__(self, prefix, string_pos):
x = []
#print("We are in the get prefix func", prefix)
for key, node in self.nodes.items():
if (string_pos >= len(prefix) or key == prefix[string_pos]):
if (node.word is not None):
x.append(node.word)
if (node.nodes != {}):
if (string_pos + 1 <= len(prefix)):
x = x + node.__get_all_with_prefix__(prefix, string_pos + 1)
else:
x = x + node.__get_all_with_prefix__(prefix, string_pos)
return x
class Trie:
def __init__(self):
self.root = Node()
def insert(self, word):
self.root.__insert__(word)
def get_all(self):
return self.root.__get_all__
def get_all_with_prefix(self, prefix, string_pos=0):
return self.root.__get_all_with_prefix__(prefix, string_pos)
root = Tk()
trie = Trie()
customFont = tkFont.Font(family="arial", size=17)
with open('words_file_for_testing.txt', mode='r') as f:
for line in f:
for word in line.split():
trie.insert(word)
def retrieve_input(self):
inputValue = content_text.get("1.0", "end-1c")
print(trie.get_all_with_prefix(inputValue))
printing_the_list(inputValue)
def printing_the_list(getinputvalue):
print(getinputvalue)
print(type(getinputvalue))
print(trie.get_all_with_prefix("A"))
print(trie.get_all_with_prefix(getinputvalue))
#print(type(words))
#print(words)
#print(trie.get_all_with_prefix("A"))
#master = Tk()
#listbox = Listbox(master)
#listbox.pack()
#for item in words:
# listbox.insert(END, item)
root.title("Autocomplete Word")
root.geometry('800x400+150+200')
content_text = Text(root, wrap='word', font=customFont)
content_text.focus_set()
content_text.pack(expand='yes', fill='both')
scroll_bar = Scrollbar(content_text)
content_text.configure(yscrollcommand=scroll_bar.set)
scroll_bar.config(command=content_text.yview)
scroll_bar.pack(side='right', fill='y')
root.bind("<space>", retrieve_input)
root.mainloop()
Now, I am having problem with its printing_the_list(getinputvalue) function. In this function, getinputvalue is the variable in which user input value is stored. When I manually entered the string to print(trie.get_all_with_prefix("A")) funtion it print the words list as desired but, when I tried to print the prefix list of words with user input value using the getinputvalue variable, got an empty list as [].
The above python code prints:
[]
A
<class 'str'>
['AAE', 'AAEE', 'AAG', 'AAF', 'AAP', 'AAPSS', 'AAM', 'AAMSI', 'AARC', 'AAII', 'AAO', 'Aar', 'Aaron', 'Aarika', 'Aargau', 'Aaren', 'Aarhus', 'Aara', 'Aarau', 'Aandahl', 'Aani', 'Aaqbiye', 'Aalesund', 'Aalto', 'Aalborg', 'Aalst', 'Aachen', 'A-and-R']
[]
What am I doing wrong.
Your problem is that when you type A and then press space
inputValue = content_text.get("1.0", "end-1c")
returns 'A ' instead of 'A'.
This is because content_text.get() adds a new line character at the end of the string. To ignore both the newline character and the space, use:
inputValue = content_text.get("1.0", "end-2c")
I've built a class for item selection with Tkinter Spinbox. I'd like to return the index of the selected item. Is that possible?
from Tkinter import *
class TestSpin():
def __init__(self, i_root, i_friendlist):
self.root = i_root
self.root.friend = Spinbox(self.root, values = i_friendlist)
self.root.friend.pack()
self.root.okbutton = Button(self.root, text='Ok', command = lambda: self.ack())
self.root.okbutton.pack()
def ack(self):
# here I'd like to have the index of selected item in friendlist
print "Index of "+self.root.friend.get()+" is [0 or 1 or 2]:", self.root.friend
# here I'd like to have the index of selected item in friendlist
self.root.destroy()
root = Tk()
list = ['Emma','Sarah','James']
app = TestSpin(root, list)
root.mainloop()
Thanks a lot for your advice. I tried self.root.friend.index(), but that method wants an argument which I do not understand.
There's no way to directly get the value from the widget, but it's just one line of python code:
index = i_fiendlist.index(self.root.friend.get())
Using your code, you need to save the value of the list:
class TestSpin():
def __init__(self, i_root,i_friendlist):
self._list = i_list
...
def ack(self):
value = self.root.friend.get()
index = self._list.index(value)
print "Index of " + value + " is " + str(index)
self.root.destroy()