My code isn't getting the values I insert into an entry

Viewed 62

I've got some code in python using tkinter which retrieves the name of a room and uses that to to insert into an SQL database the room name and which site it belongs to. However when I run the code its not retrieving the room name from the entry box.

Can anyone help?

def addroom():
    global screen14
    global roomsinsite
    roomsinsite = StringVar()
    screen14 = Tk()
    screen14.geometry("300x250")
    screen14.title("Insert rooms")
    Label(screen14, text = "Insert room name:", bg = "LightSkyBlue1", width = "300", height = "2").pack()
    Label(screen14, text = "").pack()
    roomsinsite_entry = Entry(screen14, textvariable = roomsinsite)
    roomsinsite_entry.pack()
    Button(screen14, text = "Register room", width = "12", height = "1", command = insertroom).pack()

 

def insertroom():
    sitename4_info = sitename2.get()
    print(sitename4_info)
    roomname1_info = roomsinsite.get()
    print(roomname1_info)
    cursor = cnn.cursor()
    # SQL to select the siteID and insert rooms for that paticular site.
    siteID_fetch3 = "SELECT siteID FROM Sites WHERE siteName = %s"
    cursor.execute(siteID_fetch3, [sitename4_info])
    siteID_fetch3 = cursor.fetchall()
    # print out the values retrieved
    print(siteID_fetch3[0][0])
    insertRooms = "INSERT INTO `rooms`(`siteID_fk2`, `roomname`) VALUES (%s,%s)"
    insertRooms_val = (siteID_fetch3[0][0], roomname1_info)
    cursor.execute(insertRooms, insertRooms_val)
    # print out the rows inserted.
    print(cursor.rowcount)
    cnn.commit()
1 Answers

You are probably having more than one Tk in your code, which means your StringVar does not know which Tk to belong to. So here there are three possible solutions:

  • Avoid using more than one Tk and replace all child windows with Toplevel, so:
screen14 = Toplevel()
roomsinsite = StringVar()
  • If you are adamant that you want to use more than one instance of Tk then you can specify master for each StringVar, like:
screen14 = Tk()
roomsinsite = StringVar(master=screen14)
  • To be honest, I wouldn't use StringVar with entry widgets except when I want to use trace, here if the only purpose of using StringVar is for getting the value of the entry widget, then remove it and use get() method of the entry widget, like:
roomname1_info = roomsinsite_entry.get()

The combination of first and third method seems like best practice, if you ask me. Also here, even if you are not using more than one Tk, one of the above methods would certainly solve the problem(as far as something is inputted inside the entry and then the insertroom() is called).

Related