Python Forum
[Tkinter] Inserting numbers into entry box in a widget
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tkinter] Inserting numbers into entry box in a widget
#1
Hi I am quite new to using python

I have modified and added to a pre-existing script, so there are lots of looses ends to finish.
My question is that eventually, I want to search an SQLite database and update my Tkinter widget with a count rest of the number of rows found on that search. But to aid learning all I want to do is update an entry box with a number to make sure I understand the process.

I have in def monitor an entry box and using def entry1 I can't seem to pass a result into it when I push the display counts button.
I created an account user/ password A/A to login to the second screen



#imports

from tkinter import *

from tkinter import messagebox as ms

import sqlite3



# make database and users (if not exists already) table at programme start up

with sqlite3.connect('quit.db') as db:

    c = db.cursor()



c.execute('CREATE TABLE IF NOT EXISTS user (username TEXT NOT NULL ,password TEXT NOT NULL);')

db.commit()

db.close()



#main Class

class main:

    def __init__(self,master):

        # Window 

        self.master = master

        # Some Usefull variables

        self.username = StringVar()
        
        self.level1 = StringVar()     #lets
        self.level2 = StringVar()
        self.level3 = StringVar()
        self.level4 = StringVar()  

        self.password = StringVar()

        self.n_username = StringVar()

        self.n_password = StringVar()

        #Create Widgets

        self.widgets()
        


    #Login Function

    def login(self):

        #Establish Connection

        with sqlite3.connect('quit.db') as db:

            c = db.cursor()



        #Find user If there is any take proper action

        find_user = ('SELECT * FROM user WHERE username = ? and password = ?')

        c.execute(find_user,[(self.username.get()),(self.password.get())])

        result = c.fetchall()

        if result:
            

             # self.logf.pack_forget() # Destroys frame 

              #self.log.f['text'] = self.username.get() + '\n Accsess Granted'
              self.monitor()
              
              # INSERT COUNTS HERE 
           
        else:

            ms.showerror('Oh dear!','Your names not on the list your not comming in.')

            

    def new_user(self):

        #Establish Connection

        with sqlite3.connect('quit.db') as db:

            c = db.cursor()



        #Find Existing username if any take proper action

        find_user = ('SELECT * FROM user WHERE username = ?')

        c.execute(find_user,[(self.username.get())])        

        if c.fetchall():

            ms.showerror('Error!','Username Taken Try a Diffrent One.')

        else:

            ms.showinfo('Success!','Account Created!')

            self.log()

        #Create New Account 

        insert = 'INSERT INTO user(username,password) VALUES(?,?)'

        c.execute(insert,[(self.n_username.get()),(self.n_password.get())])

        db.commit()



        #Frame Packing Methords

    def log(self):

        self.username.set('')

        self.password.set('')

        self.crf.pack_forget()

        self.head['text'] = 'LOGJDJKDJKJCIN'

        self.logf.pack()

    def cr(self):

        self.n_username.set('')

        self.n_password.set('')

        self.logf.pack_forget()

        self.head['text'] = 'Create Account'

        self.crf.pack()
    
        

        

    #Draw Widgets
        

    def widgets(self):

        self.head = Label(self.master,text = 'Login Screen',font = ('',35),pady = 10)

        self.head.pack()

        self.logf = Frame(self.master,padx =10,pady = 10)

        Label(self.logf,text = 'Username: ',font = ('',20),pady=5,padx=5).grid(sticky = W)

        Entry(self.logf,textvariable = self.username,bd = 5,font = ('',15)).grid(row=0,column=1)

        Label(self.logf,text = 'Password: ',font = ('',20),pady=5,padx=5).grid(sticky = W)

        Entry(self.logf,textvariable = self.password,bd = 5,font = ('',15),show = '*').grid(row=1,column=1)

        Button(self.logf,text = ' Login ',bd = 3 ,bg = "green" ,font = ('',15),padx=5,pady=5,command=self.login).grid()

        Button(self.logf,text = ' Create Account ',bd = 3 ,bg = "white" ,font = ('',15),padx=5,pady=5,command=self.cr).grid(row=2,column=1)

        self.logf.pack()

        
        self.crf = Frame(self.master,padx =10,pady = 10)

        Label(self.crf,text = 'Username: ',font = ('',20),pady=5,padx=5).grid(sticky = W)

        Entry(self.crf,textvariable = self.n_username,bd = 5,font = ('',15)).grid(row=0,column=1)

        Label(self.crf,text = 'Password: ',font = ('',20),pady=5,padx=5).grid(sticky = W)

        Entry(self.crf,textvariable = self.n_password,bd = 5,font = ('',15),show = '*').grid(row=1,column=1)

        Button(self.crf,text = 'Create Account',bd = 3 ,font = ('',15),padx=5,pady=5,command=self.new_user).grid()

        Button(self.crf,text = 'Go to Login',bd = 3 ,font = ('',15),padx=5,pady=5,command=self.log).grid(row=2,column=1)


    def monitor(self):
        self.logf.pack_forget() # Destroys frame
        self.head.pack_forget() # Destroys frame
        self.header = Label(self.master,text = 'Bearing defects',font = ('',35),pady = 10)

        self.header.pack()

        self.disp1 = Frame(self.master,padx =10,pady = 10)

        Label(self.disp1,text = 'Level 1: ',font = ('',20),pady=5,padx=5).grid(sticky = W)
        Label(self.disp1,text = 'Level 2: ',font = ('',20),pady=5,padx=5).grid(sticky = W)
        Label(self.disp1,text = 'Level 3: ',font = ('',20),pady=5,padx=5).grid(sticky = W)
        Label(self.disp1,text = 'Level 4: ',font = ('',20),pady=5,padx=5).grid(sticky = W)
        Entry(self.disp1,textvariable = self.level1,bd = 5,font = ('',15)).grid(row=0,column=1)
        Entry(self.disp1,textvariable = self.level2,bd = 5,font = ('',15)).grid(row=1,column=1)
        Entry(self.disp1,textvariable = self.level3,bd = 5,font = ('',15)).grid(row=2,column=1)
        Entry(self.disp1,textvariable = self.level4,bd = 5,font = ('',15)).grid(row=3,column=1)
        Button(self.disp1,text = ' Display Counts ',bd = 3 ,bg = "green" ,font = ('',15),padx=5,pady=5,command=self.level).grid()#comand delet inm sqlite3
        Button(self.disp1,text = ' Reset Database ',bd = 3 ,bg = "red" ,font = ('',15),padx=5,pady=5,command=self.wipe_data).grid(row=4,column=1)# export csv file or db file
        self.disp1.pack()
     
        
    def wipe_data(self):
      
        with sqlite3.connect('logging.db') as db:
            c = db.cursor()
            c.execute('DELETE FROM logt;',);
            db.commit()
            c.close()
            db.close()

    def export_data(self):                              #unused button define
    
         with sqlite3.connect('logging.db') as db:
            c = db.cursor()
            
    def level(self):
         #with sqlite3.connect('logging.db') as db:
         #   c = db.cursor()
         #   cur.execute("SELECT * FROM logt WHERE amps=>5")
      #Count returned rows before inserting to entry box
       #self.level1.delete(0, END)
       lv = int(4)
       self.level1.insert(0, 4)
       print("Hello World") 
        
    def level_2(self):
         with sqlite3.connect('logging.db') as db:
            c = db.cursor()
            cur.execute("SELECT * FROM logt WHERE amps=>15")
            db.commit()
            c.close()
            db.close()
    def level_3(self):
         with sqlite3.connect('logging.db') as db:
            c = db.cursor()
            cur.execute("SELECT * FROM logt WHERE amps=>35")
            db.commit()
            c.close()
            db.close()
    def level_4(self):
         with sqlite3.connect('logging.db') as db:
            c = db.cursor()
            cur.execute("SELECT * FROM logt WHERE amps=>50")
            db.commit()
            c.close()
            db.close()
#create window and application object

root = Tk()

root.title("Bearing Current Program")

main(root)

root.mainloop()
Reply
#2
You cant call insert on a StringVar it does not have this method.
Entry widgets have an insert method maybe that what you are trying to do, you will need to keep a reference to the entry widget in the class to access it.
Also note that insert parameters of a Entry are an index and a string you have used an index and a int.

https://effbot.org/tkinterbook/entry.htm...ert-method Wrote:insert(index, string)
Inserts text at the given index. Use insert(INSERT, text) to insert text at the cursor, insert(END, text) to append text to the widget.
  • index
    Where to insert the text.
  • string
    The text to insert.

All the code you posted is overwhelming and not necessary to show the problem you are having, strip out the the unnecessary parts like below.
# imports

from tkinter import *

from tkinter import messagebox as ms


# main Class

class main:

    def __init__(self, master):
        # Window
        self.master = master
        # Some Usefull variables
        self.level1 = StringVar()  # lets
        self.monitor()

    def monitor(self):

        self.disp1 = Frame(self.master, padx=10, pady=10)

        Label(self.disp1, text='Level 1: ', font=(
            '', 20), pady=5, padx=5).grid(sticky=W)
        Entry(self.disp1, textvariable=self.level1,
              bd=5, font=('', 15)).grid(row=0, column=1)
        Button(self.disp1, text=' Display Counts ', bd=3, bg="green", font=(
            '', 15), padx=5, pady=5, command=self.level).grid()  # comand delet inm sqlite3
        self.disp1.pack()

    def level(self):

        lv = int(4)
        self.level1.insert(0, 4)
        print("Hello World")


root = Tk()

root.title("Bearing Current Program")

main(root)

root.mainloop()
When you get an error post the error traceback
Error:
Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\Dave\Anaconda3\lib\tkinter\__init__.py", line 1705, in __call__ return self.func(*args) File "c:/Users/Dave/Documents/VS Code WorkSpaces/Python Forum/general/forumpost.py", line 34, in level self.level1.insert(0, 4) AttributeError: 'StringVar' object has no attribute 'insert'
It is advisable not to use star imports
https://python-forum.io/Thread-Namespace...th-imports
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  ValueError: could not convert string to float: '' fron Entry Widget russellm44 5 491 Mar-06-2024, 08:42 PM
Last Post: russellm44
  [Tkinter] entry widget DPaul 5 1,433 Jul-28-2023, 02:31 PM
Last Post: deanhystad
  Tkinter Exit Code based on Entry Widget Nu2Python 6 2,874 Oct-21-2021, 03:01 PM
Last Post: Nu2Python
  Line numbers in Text widget rfresh737 3 5,316 Apr-15-2021, 12:30 PM
Last Post: rfresh737
  method to add entries in multi columns entry frames in self widget sudeshna24 2 2,214 Feb-19-2021, 05:24 PM
Last Post: BashBedlam
  Entry Widget issue PA3040 16 6,655 Jan-20-2021, 02:21 PM
Last Post: pitterbrayn
  [Tkinter] password with Entry widget TAREKYANGUI 9 5,774 Sep-24-2020, 05:27 PM
Last Post: TAREKYANGUI
  [Tkinter] Get the last entry in my text widget Pedroski55 3 6,295 Jul-13-2020, 10:34 PM
Last Post: Pedroski55
  How to retreive the grid location of an Entry widget kenwatts275 7 4,474 Apr-24-2020, 11:39 PM
Last Post: Larz60+
  POPUP on widget Entry taratata2020 4 3,673 Mar-10-2020, 05:04 PM
Last Post: taratata2020

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020