Adding different values ​to the entries created with the loop - python

For example, I want to insert the numbers from 1 to 10, respectively, from the beginning to the end, into the 10 entries I created with a loop.
from tkinter import *
root = Tk()
root.title("")
root.geometry("500x400")
canva = Canvas(root,width=450,height=350,highlightbackground="black")
for i in range(40, 240, 21):
Abent = Entry(root, width=10)
Abentry = canva.create_window(50, i, anchor="nw", window=Abent)
Abent.insert(0,1)
canva.pack()
root.mainloop()

You can do this by using enumerate on your for loop's iterable
for index, y_pos in enumerate(range(40, 240, 21)): # enumerate over range
abent = Entry(root, width=10)
abentry = canva.create_window(50, y_pos, anchor="nw", window=abent)
abent.insert(0, index)
Also: to be compliant with PEP8, I've renamed your variables to use lowercase names! For future reference, Uppercase Names are reserved for classes like Entry

Related

Store the indices of the selected variables of a listbox in a list

I would like to save in an "indice" list all the indexes of the variables selected in the listbox. Any solution? At the moment I select a variable and it returns its index to me. I am not able to select multiple variables and save all indices in a list.
import tkinter as tk
from tkinter.constants import RIGHT, VERTICAL, Y
Ch_Output = ["a","b","c","d","e","f"]
root = tk.Tk()
root.title('Seleziona canale')
root.geometry("400x500")
var_select = str()
indice = int()
def getElement(event):
selection = event.widget.curselection()
index = selection[0]
value = event.widget.get(index)
result.set(value)
print('\n',index,' -> ',value)
global var_select
global indice
var_select = value
indice = index
#root.destroy()
# scroll bar-------
result =tk.StringVar()
my_frame = tk.Frame(root)
my_scrollbar = tk.Scrollbar(my_frame, orient=VERTICAL)
var2 = tk.StringVar()
var2.set(Ch_Output)
# list box-----------
my_listbox = tk.Listbox(my_frame, width=50, height=20, listvariable=var2)
# configure scrolbar
my_scrollbar.config(command=my_listbox.yview)
my_scrollbar.pack(side=RIGHT, fill=Y)
my_frame.pack()
my_listbox.pack(pady=15)
my_listbox.bind('<<ListboxSelect>>', getElement) #Select click
root.mainloop()
print('\n',indice)
By default, you can select only one item. If you want to select multiple items at once you need to specify selectmode to tk.MULTIPLE or tk.EXTENDED.
In your case:
import tkinter as tk
from tkinter.constants import RIGHT, VERTICAL, Y, MULTIPLE
...
selected_index = []
def getElement(event):
global selected_index
selected_index = list(event.widget.curselection())
print(selected_index)
print("Values: ", [event.widget.get(x) for x in selected_index])
...
my_listbox = tk.Listbox(my_frame, width=50, height=20, listvariable=var2, selectmode=MULTIPLE)
...
root.mainloop()

How to loop through a list in a label using Tkinter?

I am trying to create a GUI that simply prints messages after one another with some time in between.
list_of_tweets = [1, 2, 3, 4, 5]
for i in list_of_tweets:
print(i)
time.sleep(10)
window = Tk()
window.geometry("800x400")
window.title("Twitterscreen")
variable=StringVar()
def update_label():
while True:
for i in list_of_tweets:
print(i)
time.sleep(10)
variable.set(str(i))
window.update()
label = Label(master=window,
background='white',
foreground='black',
font=('Helvetica', 20),
width=14,
height=3)
label.config(width=200, height=300)
label.pack()
mainloop()
This is my code so far. When I run it, the result is just a white screen. Again, I want the label to print out the list_of_tweets one at a time with 10 seconds in between.
Start off by making your label into:
label = Label(master=window,
background='white',
foreground='black',
font=('Helvetica', 20),
width=200,
height=300)
Now the idea I'm using here is indexing the list till it reaches the last item on the list, rather than using for loop. So change your function into:
count = 0 #index number
def update_label():
global count
label.config(text=list_of_tweets[count]) #show the current indexed item
count += 1 #increase the index number
rep = window.after(1000,update_label) #repeat this process every 1 second
if count >= len(list_of_tweets): #if the index number greater than or equal to length of list
window.after_cancel(rep) #stop repeating
So final code would be:
from tkinter import *
list_of_tweets = [1, 2, 3, 4, 5]
window = Tk()
window.geometry("800x400")
window.title("Twitterscreen")
variable = StringVar() #no use here, dont know why you would use it here
count = 0
def update_label():
global count
label.config(text=list_of_tweets[count])
count += 1
rep = window.after(1000,update_label)
if count >= len(list_of_tweets):
window.after_cancel(rep)
label = Label(master=window,
background='white',
foreground='black',
font=('Helvetica', 20),
width=200,
height=300) # no need to configure it separately when you can declare it directly
label.pack()
update_label() # call the function initially
mainloop()
Why doesnt it work in your example? Firstly, your setting the value of the StringVar() into the text, correct, but that StringVar() is not associated with the label at all. And using a for loop, you would need time.sleep() but that will freeze the GUI, even if you use window.update() the window updates, but the GUI window will be unresponsive.
after(ms,func) method takes two arguments mainly:
ms - time to be run the function in millisecond(ms)
func - the function to run after the given ms is finished.
Try this for the label:
display_text = StringVar()
label=Label(window, textvariable=display_text)
text='Your message'
display_text.set(text)

Accessing Entry widget created using for loop

An array of Entries was created using the following code
from tkinter import *
root = Tk()
height = 5
width = 5
delta=0
for i in range(height): #Rows
for j in range(width): #Columns
b = Entry(root, text="",width=8)
b.grid(row=i, column=j)
mainloop()
How do I access each Entry to update its value ( using StringVar - for example ) ?
You could create a list of lists for your Entry widgets.
from tkinter import *
root = Tk()
height = 5
width = 5
delta=0
entries = []
for i in range(height): #Rows
newrow = []
for j in range(width): #Columns
b = Entry(root, text="",width=8)
b.grid(row=i, column=j)
newrow.append(b)
entries.append(newrow)
mainloop()
You could then address individual entries as e.g. entries[2][4].
Edit: To edit the text of entry widget e, first use e.delete(0, END) to clear it, and then use e.insert(0, "new text") to insert new text.
Edit2: Alternatively, you could store the StringVars in a list of lists instead of the widgets...
You need to first declare the StringVar variable:
myvar = StringVar()
Then in your loop whenever you want to check to content of the variable use the get() method.
x = myvar.get()
Now x will hold the value. You can also perform a bool test with if
if myvar.get():
print(myvar.get())
In that if statement the program checks if there is data in the var. If not it will move on
Looking at it again you should also declare the StringVar() in your button. Like so:
b = Button(text='clickme', texvariable=myvar)
Look Here for more info

Change the order of switching tkinter.spinbox "values"

I need to change the order of switching values in Spinbox widget, in case, when "values" parametr is set. This could be similar like a "increment=-1", when using "from_" and "to" paramentrs. I want, just the opposite, when i'm clicking "downbutton" - index of values is increaseing...
from tkinter import *
root = Tk()
var = StringVar()
values = ['1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript']
spin_box = Spinbox(root,
textvariable=var,
values=values,
wrap=True,
command=lambda: print(var.get()),
width=12)
spin_box.pack()
root.mainloop()
Just reverse your list, and initialize the value with the last item in the reversed list. It doesn't change the index of the selected item per se, but it makes the down arrow move through the list in the opposite way.
from tkinter import *
root = Tk()
values = ['1.Python','2.Ruby','3.PHP','4.Perl','5.JavaScript']
values = values[::-1]
var = StringVar()
spin_box = Spinbox(root,
textvariable=var,
values=values,
wrap=True,
command=lambda: print(var.get()),
width=12)
var.set(values[-1])
spin_box.pack(padx=50, pady=50)
root.mainloop()

Python tkinter, grid manager is not working

import tkinter
from tkinter import *
root = Tk()
root.geometry("500x500")
root.title("Insert title")
root.configure(background='#CCCCFF')
label1 = Label(root, text = "Insert title", font = ("Rockwell", 12))
label2 = Label(root, text = "Name", font = ("Rockwell", 25))
label1.configure(background='#CCCCFF')
label2.configure(background = '#CCCCFF')
label1.grid(row = 8, column = 3)
root.mainloop()
Every time I change the settings for the grid manager for label2, the label always stays in the same place. How can I fix this?
If you're asking "why does my 'Insert title' label always appear in the upper left corner, even though it has large row and column values?", it's because totally empty rows and columns are squashed down to zero pixels, so the eighth row will appear to be the first row, if rows 1 through 7 don't have any widgets in them.
One possible workaround is to add placeholder widgets to each row and column that you don't want to collapse.
import tkinter
from tkinter import *
root = Tk()
root.geometry("500x500")
root.title("Insert title")
root.configure(background='#CCCCFF')
for i in range(10):
Frame(root, width=20, height=20, background='#CCCCFF').grid(row=0, column=i)
for j in range(10):
Frame(root, width=20, height=20, background='#CCCCFF').grid(column=0, row=j)
label1 = Label(root, text = "Insert title", font = ("Rockwell", 12))
label2 = Label(root, text = "Name", font = ("Rockwell", 25))
label1.configure(background='#CCCCFF')
label2.configure(background = '#CCCCFF')
label1.grid(row = 8, column = 3)
label2.grid(row = 9, column = 3)
root.mainloop()
if a row or column is completely empty, it's size will be zero. So even though you put something in row 8, rows zero through seven are non-existent. The same goes for the columns.

Categories

Resources