Printing tkinter label in new line - python

First of all, sorry for that vague title. I am making a python application that shows time, fetches weather and News. Now, when i print news through tkinter label, it prints the titles of news on a separate line but in the center. If I try to specify the .pack(side=LEFT) geometry, it goes to the left but all the headlines print in a string and not in a newline. I have tried adding new line by '\n' and even carriage return '\n' but in vain. Please help me out with this issue. Attaching the code below.
P.s i could not get it the news to work with the For loop so i manually printed arrays.
from tkinter import *
import datetime
from PIL import Image, ImageTk
import requests
class Clock(Frame):
def __init__(self, parent):
Frame.__init__(self,parent, bg='black')
self.now = datetime.datetime.today()
self.time = str(self.now.hour) + ":" + str(self.now.minute)
self.timelb = Label(self, text=self.time, font=("Helvetica 50"), bg='black', fg='white')
self.timelb.pack(anchor=NE,padx=60,pady=0)
self.date = str(self.now.day) + '.' + str(self.now.month) + '.' + str(self.now.year)
self.day = self.now.strftime('%A')
self.daylb = Label(self, text=self.day, font="Helvetica 20", bg='black', fg='white')
self.daylb.pack(anchor=NE,padx=60)
self.datelb = Label(self, text=self.date, font="Helvetica 25", bg = 'black', fg='white')
self.datelb.pack(anchor=NE, padx=60)
class Weather(Frame):
def __init__(self, parent):
Frame.__init__(self,parent,bg='black')
url = 'http://api.openweathermap.org/data/2.5/weather?appid=c73d9cdb31fd6a386bee66158b116cd0&q=Karachi&units=metric'
json = requests.get(url).json()
temperature = json['main']['temp']
description = json['weather'][0]['description']
icon_id = json['weather'][0]['icon']
city = 'Karachi'
icon_url = ('http://openweathermap.org/img/wn/{icon}#2x.png'.format(icon=icon_id))
self.im = Image.open(requests.get(icon_url, stream=True).raw)
self.ph = ImageTk.PhotoImage(self.im)
degree = u'\N{DEGREE SIGN}' + 'C'
self.pic_label = Label(self,image=self.ph,bg='black')
self.pic_label.pack()
self.lab= Label(self,text=(str(temperature) + degree),font=("Helvetica 40"), bg='black', fg='white')
self.lab.pack()
self.description_label=Label(self, text=description, font='Helvetica 20',bg='black', fg='white')
self.description_label.pack()
self.city_label=Label(self, text=city, font = 'Helvetica 10', bg='black', fg='white')
self.city_label.pack()
class News(Frame):
def __init__(self, parent):
super(News, self).__init__(bg='black')
url = " https://newsapi.org/v1/articles?source=bbc-news&sortBy=top&apiKey=caa7f97ce8f2400a9785cbe704afc345"
json = requests.get(url).json()
self.title = 'Headlines'
self.title_lb = Label(self, text=self.title, font='Helvetica 25',bg='black', fg='white')
self.title_lb.pack(side=TOP, anchor=N)
im = Image.open('Newspaper_reduced.png')
self.pho = ImageTk.PhotoImage(im)
news1 = json['articles'][0]['title']
news2 = json['articles'][1]['title']
news3 = json['articles'][2]['title']
news4 = json['articles'][3]['title']
news5 = json['articles'][4]['title']
self.img = Label(self,image=self.pho,bg='black')
self.img.pack(side=LEFT)
self.headline1_lb = Label(self, text=news1, font = 'Helvetica 15' ,bg='black', fg='white')
self.headline1_lb.pack(side=LEFT)
self.img2 = Label(self,image=self.pho,bg='black')
self.img2.pack(side=LEFT)
self.headline2_lb = Label(self, text = news2, font='Helvetica 15',bg='black', fg='white')
self.headline2_lb.pack(side=LEFT)
self.img3 = Label(self,image=self.pho,bg='black')
self.img3.pack(side=LEFT)
self.headlines3_lb = Label(self, text=news3, font='Helvetica 15',bg='black', fg='white')
self.headlines3_lb.pack(side=LEFT)
self.img4 = Label(self,image=self.pho,bg='black')
self.img4.pack(side=LEFT)
self.headlines4_lb = Label(self, text=news4, font='Helvetica 15',bg='black', fg='white')
self.headlines4_lb.pack(side=LEFT)
self.img5 = Label(self,image=self.pho,bg='black')
self.img5.pack(side=LEFT)
self.headlines5_lb = Label(self, text=news5, font='Helvetica 15',bg='black', fg='white')
self.headlines5_lb.pack(side=LEFT)
class Fullscreen:
def __init__(self):
self.tk = Tk()
self.tk.configure(bg='black')
self.tk.title('smartmirror')
self.topFrame = Frame(self.tk , bg='black')
self.topFrame.pack(side=TOP, fill=BOTH, expand=YES)
self.bottomFrame = Frame(self.tk, bg='black')
self.bottomFrame.pack(side=BOTTOM, fill=BOTH, expand=YES)
self.clock = Clock(self.topFrame)
self.clock.pack(side=RIGHT, anchor=NE, padx=50, pady=60)
self.weather = Weather(self.topFrame)
self.weather.pack(side=LEFT, anchor=NW, padx=50, pady=70)
self.news = News(self.bottomFrame)
self.news.pack(side=BOTTOM, anchor=S)
if __name__ == '__main__':
w = Fullscreen()
w.tk.mainloop

First: I removed images in code because I don't have them and I want to waste time to search images which I could use as replacement.
If you set different color for labels then you see then have different width - they use width of text.
If you use
self.headline1_lb.pack(fill='x')
then they will use the same width but text still is in center.
If you use
Label(..., anchor='w')
then it will move text to left side.
If you will put in Label text with many lines then you may need also
Label(..., anchor='w', justify='left')
If you want use full width of window for text then you have to use fill='x'
self.news.pack(side=BOTTOM, anchor='s', fill='x')
After that you can again set black background.

Related

make tkinter window shrink, as widgets are deleted

I'm making some program, where I input a bunch of stuff into an entry and it gets printed into a row. I also added a feature where you can delete a row. However, when I delete a row, the window does not shrink. The way I actually made the program was by having 2 frames; the main frame with the buttons and entries, and the output or text frame. When I delete a row, it actually appends the data from a list, deletes the frame and all the widgets and reprints the rows, but with out the row I deleted.
The issue with my code, is that when I delete a row, the rows that weren't deleted start to get smaller and compress and secondly, the bottom of the window doesn't move upwards, leaving a blank white space.
Any help would be appreciated, thanks.
actually appending, labelling and printing the row is in function append_entry() and my delete function is delete_row()
from tkinter import *
global main_window
def quit():
main_window.destroy()
def entry_labels():
leader_label = Label(main_frame, text = 'Customer Name')
leader_label.grid(column=0, row=0)
location_label = Label(main_frame, text = 'Receipt Number')
location_label.grid(column=0, row=1)
numcampers_label = Label(main_frame, text = 'Item Hired')
numcampers_label.grid(column=0, row=2)
weather_label = Label(main_frame, text = 'Number Hired')
weather_label.grid(column=0, row=3)
row_label = Label(main_frame, text= 'Row')
row_label.grid(column=3, row=2)
def button():
print_button = Button(main_frame, text = "Print Details", command = append_entry)
print_button.grid(column=3, row=1)
quit_button = Button(main_frame, text= "Quit", command=quit)
quit_button.grid(column=4, row=0)
delete_row_button = Button(main_frame, text = 'Delete Row', command = delete_row)
delete_row_button.grid(column=4, row=3)
def entry():
global name_entry
name_entry = Entry(main_frame)
name_entry.grid(column=1, row=0)
global receipt_entry
receipt_entry = Entry(main_frame)
receipt_entry.grid(column=1, row=1)
global hired_entry
hired_entry = Entry(main_frame)
hired_entry.grid(column=1, row=2)
global num_hired_entry
num_hired_entry = Entry(main_frame)
num_hired_entry.grid(column=1, row=3)
global delete_row_entry
delete_row_entry = Entry(main_frame)
delete_row_entry.grid(column=4, row=2)
def table_headers():
row_header = Label(main_frame, text='Row', font = 'Arial 10 bold')
row_header.grid(column=0, row=4)
customer_header = Label(main_frame, text='Customer Name', font = 'Arial 10 bold')
customer_header.grid(column=1, row=4)
receipt_header = Label(main_frame, text='Receipt Number', font = 'Arial 10 bold')
receipt_header.grid(column=3, row=4)
item_header = Label(main_frame, text='Item Hired', font = 'Arial 10 bold')
item_header.grid(column=2, row=4)
num_header = Label(main_frame, text='Number Hired', font = 'Arial 10 bold')
num_header.grid(column=4, row=4)
def append_entry():
global second_frame
second_frame = Frame(main_window)
second_frame.grid(column=0, row=6)
leader_error_var.set("")
location_error_var.set("")
numcamper_error_var.set("")
weather_error_var.set("")
global name_count
name_count = 0
global ROWS_ABOVE
ROWS_ABOVE = 6
try:
name_entry_str = str(name_entry.get())
hired_entry_str = str(hired_entry.get())
receipt_entry_int = str(receipt_entry.get())
num_hired_entry_int = str(num_hired_entry.get())
if len(name_entry.get()) != 0:
input_data_col1.append([name_entry_str])
input_data_col2.append([hired_entry_str])
input_data_col3.append([receipt_entry_int])
input_data_col4.append([num_hired_entry_int])
counters['total_entries'] += 1
print(input_data_col1)
print(input_data_col2)
print(input_data_col3)
print(input_data_col4)
while name_count < counters ['total_entries']:
global name
name = Label(second_frame, text=(input_data_col1[name_count][-1])) ##using -1 selects the latest entry in the list
name.grid(column=1, row=name_count + ROWS_ABOVE, padx=50)
item = Label(second_frame, text=(input_data_col2[name_count][-1]))
item.grid(column=2, row=name_count + ROWS_ABOVE, padx=50)
row = Label(second_frame, text=name_count)
row.grid(column=0, row=name_count + ROWS_ABOVE, padx=60)
receipt = Label(second_frame, text=(input_data_col3[name_count][-1]))
receipt.grid(column=3, row=name_count + ROWS_ABOVE, padx=50)
num = Label(second_frame, text=(input_data_col4[name_count][-1]))
num.grid(column=4, row= name_count + ROWS_ABOVE, padx=50)
name_count += 1
name_entry.delete(0,END)
receipt_entry.delete(0,END)
hired_entry.delete(0,END)
num_hired_entry.delete(0,END)
except:
leader_error_var.set("Check inputs")
#location_error_var.set("please enter a valid num")
#numcamper_error_var.set("numcamper error test")
weather_error_var.set("")
name_entry.delete(0,END)
receipt_entry.delete(0,END)
hired_entry.delete(0,END)
num_hired_entry.delete(0,END)
def delete_row():
user_del =int(delete_row_entry.get())
counters['total_entries'] -= 1
input_data_col1.pop(user_del)
input_data_col2.pop(user_del)
input_data_col3.pop(user_del)
input_data_col4.pop(user_del)
data = [input_data_col1,input_data_col2,input_data_col3,input_data_col4]
for widget in second_frame.winfo_children():
widget.destroy()
append_entry()
print(input_data_col1)
print(input_data_col2)
print(input_data_col3)
print(input_data_col4)
def error_prevention():
#leader_error_var.set("leader error test")
#location_error_var.set("location error test")
#numcamper_error_var.set("numcamper error test")
#weather_error_var.set("weather error test")
#weather_error_var.set("_______________")
leader_error = Label(main_frame, textvariable = leader_error_var, fg = 'red')
leader_error.grid(column=2, row=0)
location_error = Label(main_frame, textvariable = location_error_var, fg = 'red')
location_error.grid(column=2, row=1)
numcamper_error = Label(main_frame, textvariable = numcamper_error_var, fg = 'red', width = 13)
numcamper_error.grid(column=2, row=2)
weather_error = Label(main_frame, textvariable = weather_error_var, fg = 'red')
weather_error.grid(column=2, row=3)
def main():
global main_window
main_window = Tk()
global input_data_col1
input_data_col1 = []
global input_data_col2
input_data_col2 = []
global input_data_col3
input_data_col3 = []
global input_data_col4
input_data_col4 = []
global input_data
input_data = []
global main_frame
main_frame = Frame(main_window)
main_frame.grid(row=0,column=0)
global counters
counters = {'total_entries':0, 'name_count':0}
#global number
#number = {'total_entries':0}
def stringvars():
global location_error_var
location_error_var = StringVar()
location_error_var.set("")
global numcamper_error_var
numcamper_error_var = StringVar()
numcamper_error_var.set("")
global leader_error_var
leader_error_var = StringVar()
leader_error_var.set("")
global weather_error_var
weather_error_var = StringVar()
leader_error_var.set("")
stringvars()
entry_labels()
entry()
error_prevention()
button()
table_headers()
main()
main_window.mainloop()
Under the code
for widget in second_frame.winfo_children():
widget.destroy()
add this block of code
second_frame.pack()
it will be like this
for widget in second_frame.winfo_children():
widget.destroy()
second_frame.pack()
I hope this helps you
You can use
main_window.geometry("1200x800+100+100")
to change size and position of main_window. Here the window width will be 1200 and height will be 800, positioned 100px to the top left corner of screen. The +100+100 is optional.
You may add geometry() to delete_row callback to resize the frame. Though you might have to calculate the proper size after widget deletion.
As to "when I delete a row, the rows that weren't deleted start to get smaller and compress",
That's due to how grid layout works. If there are two widgets on the same grid row, the grid height will be equal the the higher widget height. When the higher widget is removed, the grid will resize to the smaller widget height and appear to 'shrink'.
To solve that, you can try add padding to the widget, the syntax is
widget.grid(column=1,row=1,padx=(10,10),pady=(10,10))
Alternatively, you may try other layout management: .place will give you absolute layout control. Or you can use pack and let tkinter decide the proper position.

Set string to text in idle

Am new to this so apologies for the basic question
I am trying to set an input box to take letters and numbers
Unfortunately I can only set this field to numbers by using str()
I have tried messing with the code but it will not allow me to use letters
What should I be using instead of str()?
As you can see in my code example, I can only set the username and password to a numerical value rather than alpha numeric values
I believe that I have imported all the correct modules from tk
Have I set the below definitions incorrectly?
- self.Username = StringVar()
- self.Password = StringVar()
Thanks
from tkinter import*
import tkinter.messagebox
from tkinter import ttk
import random
import time
import datetime
def main():
root = Tk()
app = Window1(root)
class Window1:
def __init__(self, master):
self.master =master
self.master.title("Notification Monitoring System")
self.master.geometry('1350x750+0+0')
self.master.config(bg ='white')
self.frame = Frame(self.master, bg ='white')
self.frame.pack()
self.Username = StringVar()
self.Password = StringVar()
self.lblTitle = Label(self.frame, text = 'Welcome to Notification Monitoring', font=('arial',50,'bold'), bg='white',
fg='black')
self.lblTitle.grid(row=0, column=0, columnspan=2, pady=40)
#==============================Frames================================================================
self.LoginFrame1 = LabelFrame(self.frame, width=1350, height=600
,font=('arial',20,'bold'),relief='ridge',bg='pale green', bd=20)
self.LoginFrame1.grid(row=1, column=0)
self.LoginFrame2 = LabelFrame(self.frame, width=1000, height=600
,font=('arial',20,'bold'),relief='ridge',bg='pale green', bd=20)
self.LoginFrame2.grid(row=2, column=0)
#==============================Label And Entry=======================================================
self.lblUsername=Label(self.LoginFrame1, text = 'Username',font=('arial',20,'bold'),bd=22,
bg='pale green', fg='black')
self.lblUsername.grid(row=0,column=0)
self.txtUsername=Entry(self.LoginFrame1,font=('arial',20,'bold'),textvariable= self.Username)
self.txtUsername.grid(row=0,column=1, padx=119)
self.lblPassword=Label(self.LoginFrame1, text = 'Password',font=('arial',20,'bold'),bd=22,
bg='pale green', fg='black')
self.lblPassword.grid(row=1,column=0)
self.txtPassword=Entry(self.LoginFrame1,font=('arial',20,'bold'),show='*', textvariable= self.Password)
self.txtPassword.grid(row=1,column=1, columnspan=2, pady=30)
#==============================Buttons===============================================================
self.btnLogin = Button(self.LoginFrame2, text = 'Login', width = 17,font=('arial',20,'bold'),
command =self.Login_System)
self.btnLogin.grid(row=3,column=0, pady=20, padx=8)
self.btnReset = Button(self.LoginFrame2, text = 'Clear', width = 17,font=('arial',20,'bold'),
command =self.Reset)
self.btnReset.grid(row=3,column=1, pady=20, padx=8)
self.btnExit = Button(self.LoginFrame2, text = 'Exit', width = 17,font=('arial',20,'bold'),
command =self.iExit)
self.btnExit.grid(row=3,column=2, pady=20, padx=8)
#==============================Buttons===========================================================
def Login_System(self):
u =(self.Username.get())
p =(self.Password.get())
if (u ==str(123456789) and p ==str(987654321)):
self.newWindow = Toplevel(self.master)
self.app = Window2(self.newWindow)
else:
tkinter.messagebox.askyesno("Notification Monitoring System", "Invalid login details")
self.Username.set("")
self.Password.set("")
self.txtUsername.focus()
def Reset(self):
self.Username.set("")
self.Password.set("")
self.txtUsername.focus()
def iExit(self):
self.iExit = tkinter.messagebox.askyesno("Notification Monitoring System", "Confirm you want to exit")
if self.iExit > 0:
self.master.destroy()
else:
command = self.new_window
return
def new_window(self):
self.newWindow = Toplevel(self.master)
self.app = Window2(self.newWindow)
class Window2:
def __init__(self, master):
self.master =master
self.master.title("Notification Monitoring System")
self.master.geometry('1350x750+0+0')
self.master.config(bg ='cadet blue')
self.frame = Frame(self.master, bg ='powder blue')
self.frame.pack()
#====================================================================================================
#==============================New window code here==================================================
#===================================================================================================
if __name__== '__main__':
root = Tk()
application = Window1(root)
root.mainloop()
Your question is unclear but I'll try and answer it.
To take input as a number, use:
>>>a = int(input("Enter :"))
Enter :5
>>>print(a*5)
25

Scrollbar with tkinter messing up

The code below was originally developed to understand how to render a list of urls in a frame and access them by clicking on them. I also had a few buttons to score them. In my project, I have now a long number of urls and need a scrollbar to access them. I have added one, but the urls are not rendered in the part of the frame where the scollbar can be used. In fact, I would like the entire bottomframe to be linked to the scrollbar and used to render the list of urls. I do not understand what I have done wrong. Could anyone help me please?
EDIT: following the answer below, the code below is now working
import tkinter as tk
import webbrowser
class Pierre:
"""This class holds all the objects, data and functions for a single line"""
def __init__(self, master, url):
self.url = url
self.counter = 0
_, i = master.grid_size() # get the current row number
lbl = tk.Label(master, text=url, fg="blue", cursor="hand2")
lbl.grid(row=i, column=0)
lbl.bind("<Button-1>", self.callback)
self.DisplayButton = tk.Button(master, text = self.counter)
self.DisplayButton.grid(row=i, column=1)
self.DisplayButton.config(height = 1, width = 1 )
self.Plus1Button = tk.Button(master, text = "+1", command=self.plus1, bg="green")
self.Plus1Button.grid(row=i, column=2)
self.Plus1Button.config(height = 1, width = 1 )
self.Neg1Button = tk.Button(master, text = "-1", command=self.neg1, bg="green")
self.Neg1Button.grid(row=i, column=3)
self.Neg1Button.config(height = 1, width = 1 )
master.update_idletasks()
def plus1(self):
self.counter += 1
self.DisplayButton["text"]=str(self.counter)
def neg1(self):
self.counter -= 1
self.DisplayButton["text"]=str(self.counter)
def callback(self, event):
webbrowser.open_new(self.url)
class TestClass(tk.Tk):
def __init__(self, **kwargs):
tk.Tk.__init__(self, **kwargs)
self.title('Test')
self.topframe = tk.Frame(self)
self.topframe.pack( side = tk.TOP, pady=30)
self.bottomframe = tk.Frame(self, width=250, height=190, bg="#EBEBEB")
self.bottomframe.pack( side = tk.BOTTOM )
self.canvas = tk.Canvas(self.bottomframe, width=250, height=190,
scrollregion=(0, 0, 1200, 800))
self.canvas.grid()
self.vscrollbar = tk.Scrollbar(self.bottomframe, orient=tk.VERTICAL,
command=self.canvas.yview)
self.vscrollbar.grid(row=0, column=5, sticky=tk.N+tk.S)
self.canvas['yscrollcommand'] = self.vscrollbar.set
self.frameCanvas=tk.Frame(self.canvas)
self.canvas.create_window((0,0),window=self.frameCanvas,anchor='nw')
#self.canvas.configure(scrollregion=self.canvas.bbox("all"))
self.button = tk.Button(self.topframe, text='Click', command = self.output_value)
self.button.pack(side="left", fill="both", expand=True)
####define the function that the submit button will do
def output_value(self):
urls = ["http://www.google.com", "http://www.facebook.com","http://www.google.com", "http://www.facebook.com", "http://www.google.com", "http://www.facebook.com"]
for url in urls:
Pierre(self.frameCanvas, url)
if __name__ == "__main__":
root = TestClass()
root.mainloop()
Frames do not have scrolling ability. The usual way is to use a canvas and then to place widgets on the canvas with create_window().

Discussion with tkinter

from tkinter import *
window = Tk()
ia_answers= "trolol"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)
input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)
ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)
user_says = StringVar()
user_text = Label(ia_frame, textvariable=user_says, anchor = NE, justify = RIGHT, bg="white")
user_text.pack(fill=BOTH, side=TOP)
ia_says = StringVar()
ia_text = Label(ia_frame, textvariable=ia_says, anchor = W, justify = LEFT, bg="white")
ia_text.pack(fill=BOTH, side=BOTTOM)
def Enter_pressed(event):
"""Took the current string in the Entry field."""
input_get = input_field.get()
input_user.set("")
user_says.set(input_get + "\n\n")
ia_says.set(ia_answers)
input_field.bind("<Return>", Enter_pressed)
window.mainloop()
Hi, i am trying to build a discussion Bot.
When I execute the code, the question in the input field and the answer get displayed correctly.
The problem is after entering the next sentence, the previous question/answer gets removed. Here is an example:
Hello Bot
Hello User
(then the text disappears)
How are you
Fine thank you
What i want :
Hello Bot
Hello User
(then the text stays in the frame)
How are you
Fine thank you
The issue occurs in line -
user_says.set(input_get + "\n\n")
ia_says.set(ia_answers)
You are replace users_says.set() and ia_says.set() resets the complete Labels , with the new value. Instead you should get the old value and append the new value to it and set it back, Example -
user_says.set(user_says.get() + input_get + "\n")
ia_says.set(ia_says.get() + ia_answers + "\n")
Or you can also create a new label for each new event and add it to the LabelFrame . Example -
from tkinter import *
window = Tk()
ia_answers= "trolol\n"
input_frame = LabelFrame(window, text="User :", borderwidth=4)
input_frame.pack(fill=BOTH, side=BOTTOM)
input_user = StringVar()
input_field = Entry(input_frame, text=input_user)
input_field.pack(fill=BOTH, side=BOTTOM)
ia_frame = LabelFrame(window, text="Discussion",borderwidth = 15, height = 100, width = 100)
ia_frame.pack(fill=BOTH, side=TOP)
user_says = StringVar()
user_text = Label(ia_frame, textvariable=user_says, anchor = NE, justify = RIGHT,
bg="white")
user_text.pack(fill=X)
ia_says = StringVar()
ia_text = Label(ia_frame, textvariable=ia_says, anchor = NW, justify = LEFT, bg="white")
ia_text.pack(fill=X)
user_texts = []
ia_texts = []
user_says_list = []
ia_says_list = []
def Enter_pressed(event):
"""Took the current string in the Entry field."""
input_get = input_field.get()
input_user.set("")
user_says1 = StringVar()
user_says1.set(input_get + "\n")
user_text1 = Label(ia_frame, textvariable=user_says1, anchor = NE, justify = RIGHT,
bg="white")
user_text1.pack(fill=X)
user_texts.append(user_text1)
user_says_list.append(user_says1)
ia_says1 = StringVar()
ia_says1.set(ia_answers)
ia_text1 = Label(ia_frame, textvariable=ia_says1, anchor = NW, justify = LEFT,
bg="white")
ia_text1.pack(fill=X)
ia_texts.append(ia_text1)
ia_says_list.append(ia_says1)
input_field.bind("<Return>", Enter_pressed)
window.mainloop()

How to store values from an Entry widget for loop in tkinter?

This should be a very very simple problem. I'm making a GUI in which I have multiple entry widgets... about 30 or so all in one column. Instead of making each box one by one it seems like a better idea to just generate the widgets with a loop. However, I'm finding it extremely difficult to .get() values from the entry widgets, and convert them into floats. This is what I have so far... any help would be greatly appreciated.
class Application(Frame):
def __init__(root,master):
Frame.__init__(root,master)
root.grid()
root.create_widgets()
def calcCR(root):
d1 = root.enter.get()
d1 = float(d1)
#root.answer.delete(0.0,END)
a = 'The C/R Alpha is! %lf \n' % (d1)
root.answer.insert(0.0, a)
def create_widgets(root):
### Generate Element List ###
for i in range(len(elem)):
Label(root, text=elem[i]).grid(row=i+1, column=0)
### Generate entry boxes for element wt% ###
for i in range(len(elem)):
enter = Entry(root, width = 8)
enter.grid(row = i+1,column=1)
enter.insert(0,'0.00')
root.button = Button(root, text = 'Calculate C/R', command = root.calcCR)
root.button.grid(row=11, column=2, sticky = W, padx = 10)
root.answer = Text(root, width = 50, height = 12.5, wrap = WORD)
root.answer.grid(row=1, column=2, rowspan = 10, sticky = W, padx = 10)
root = Tk()
root.title('C/R Calculator')
app = Application(root)
root.mainloop()
Put the Entry instances into a list.
from tkinter import Tk, Frame, Label, Entry, Button
class App(Frame):
def __init__(root, master):
Frame.__init__(root, master)
root.grid()
root.create_widgets()
def get_values(root):
return [float(entry.get()) for entry in root.entries]
def calc_CR(root):
answer = sum(root.get_values()) #Replace with your own calculations
root.answer.config(text=str(answer))
def create_widgets(root):
root.entries = []
for i in range(20):
label = Label(root, text=str(i))
label.grid(row=i, column=0)
entry = Entry(root, width=8)
entry.grid(row=i, column=1)
entry.insert(0, '0.00')
root.entries.append(entry)
root.calc_button = Button(root, text='Calculate C/R', command=root.calc_CR)
root.calc_button.grid(row=20, column=0)
root.answer = Label(root, text='0')
root.answer.grid(row=20, column=1)
def run(root):
root.mainloop()
root = Tk()
root.title('C/R Calculator')
app = App(root)
app.run()

Categories