Bottom Page

Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
 [Tkinter] entry filed sum
#1
Hi, trying to learn python and have stuck with entry fields.

I am trying to create a button so the user can add an entry field and write the number in it.
So far I made some progress, but can't figure out how to declare InitVar() for every EntryField so I can summarize user's input.
Or am I doing it totally wrong...
I'll be grateful for any guidance

Heres the code:


import tkinter as tk
from tkinter import *


root = tk.Tk()
root.configure(bg = "#282930")

class Stavka:
    all_entries = [1]
    user_ent = IntVar()
    def __init__(self, master):
        self.addboxButton = Button(master, text='Add +', bg="#282930", fg="white", command=self.addBox)
        self.addboxButton.grid(row=0, column=0, sticky="E")


    def addBox(self):

        nextcolumn = len(self.all_entries)
        # add entry in second row
        self.ent = Entry(root, textvariable=self.user_ent, width=80)
        self.ent.grid(row=nextcolumn, column=1)
        self.all_entries.append( ent )


pred_ent = IntVar()
ent = Entry(root, textvariable=pred_ent, width=80)
ent.grid(row=0, column=1)

s = Stavka(root)


root.mainloop()
Quote
#2
You would have something like ths:
values= []

def addentry()
     value= StringVar()
     Entry(root, textvariable=value).grid(row=len(entries), column=1)
     values.append(value)
If you want you can keep a handle for each Entry, but once they are created the variable is all you really need. To clear all the entries set all the variables to ''. To sum all the entries loop through the variables, convert the string to a number and add.

Whenever you have a collection of items that can grow arbitrarily think about using a list or a dictionary to hold your collection.
Quote
#3
Thanks deanhystad, but as I am still learning and I don't wont to be spoiled, but can you please explain it,
How I should call that function should it be part of the class or should I create another event to call that function?
And why should it be StringVar() rather than IntVar()
I want to understand so I can progress.
How to solve the problem with EntryField that from the second field to the last one I am getting the same input value.
Thanks in advance
Quote
#4
I read up a bit on Tk variables and you are correct. IntVar or DoubleVar are better choices for your program. I thought the variable had to match the data type for the widget, but that is incorrect. Tk Variables are a lot smarter and more useful than I thought. Thanks for pointing this out.

I took some time to think about how my new Variables knowledge would affect my approach to writing your program and I came up with this:
import tkinter as tk
from tkinter import *
 
class Stavka:
    def __init__(self, window):
        self.window = window
        self.entries = []
        self.addVariable()

        # Display sum of all entries in top row.  Use self.sum
        # to set label text to display sum of all entries
        self.sum = StringVar()
        Label(self.window, text= 'Sum of all Variables') \
                           .grid(row=0, column=0)
        Label(self.window, textvariable=self.sum) \
                           .grid(row=0, column=1)
        self.sum.set(0.0)

        # A button to add an entry field
        Button(self.window, text='Add Veriable',
               command=self.addVariable, width=20) \
               .grid(row=1, column=0)

        # A button to set all entries to 0.0
        b = Button(self.window, text='Reset Variables',
                   command=self.resetVariables, width=20) \
                   .grid(row=2, column=0)

    def addVariable(self):
        """Create a new entry field"""
        # Create a Tk Variable to get/set the entry
        entry = DoubleVar()
        entry.trace_add('write', self.computeSum)
        self.entries.append(entry)

        row = len(self.entries)
        Label(self.window, text=f' Variable {row} ').grid(row=row, column=1)
        # Create entry.  Bind to variable.  Place in right column
        Entry(self.window, textvariable=entry, width=10) \
              .grid(row=row, column=2)

    def computeSum(self, var, index, mode):
        """Compute sum of all entry fields"""
        sum = 0.0
        try:
            for var in self.entries:
                sum += var.get()
        except:
            pass
        self.sum.set(str(sum))
 
    def resetVariables(self):
        """Set all entry fields to 0.0"""
        for var in self.entries:
            var.set(0.0)
 
root = tk.Tk()
s = Stavka(root)
root.mainloop()
This may be a bit extreme. I'm not maintaining handles to any of the widgets and everything is done using variables. If you wanted a way to delete entries from the panel or do have any features that need access the widgets (perhaps a button for deleting entries) you would need to keep a list of Entry's and variable Label's.
Quote
#5
Thank you deanhystad, this approach is nice.
Quote

Top Page

Possibly Related Threads...
Thread Author Replies Views Last Post
  Transfer Toplevel window entry to root window entry with TKinter HBH 0 1,032 Jan-23-2020, 09:00 PM
Last Post: HBH
  [Tkinter] how to get the entry information using Entry.get() ? SamyPyth 2 991 Mar-18-2019, 05:36 PM
Last Post: woooee

Forum Jump:


Users browsing this thread: 1 Guest(s)