Python Forum

Full Version: ValueError: could not convert string to float:
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i tried to write a small program using tkinter and other small libraries, but i ran into a problem converting the string into a float in line 13, could anyone help? there might be some other inconsistencies in the program as well (because i didnt really finish it yet), if you can also help me with those, that would be awesome, thank you!

import tkinter as tk
import random
import time
window = tk.Tk()

def startthing():
    random_float = random.random() + 1
    limit = random.randint(0,10)
    x = 0
    bet = bettingentry.get()
    value = int(rising["text"])
    while x!=limit:
        betting["text"] = (float(bet) * random_float)
        x = x + 1
        time.sleep(1)
    


rising = tk.Label(text = 1)
rising.pack()

betting = tk.Label(text = 0)
betting.pack()

bettingentry = tk.Entry()
bettingentry.pack()

buttonentry = tk.Button(
    text = "bet the money /",
    command = startthing()
)
buttonentry.pack()
buttonentry.bind("<Button-1>", startthing())

window.geometry('500x500')
window.mainloop()
Error:
File "/Users/nope/Desktop/testing_app.py", line 13, in startthing betting["text"] = (float(bet) * random_float) ValueError: could not convert string to float:
The exception message tells you that what you're passing to float is the empty string (else you'd see the string you're passing). I don't know Tkinter, so it's not obvious to me what's wrong, other than the field just being empty of course.
Looks like the bet is a string ,i.e., like a word or something, which cannot be converted into a floating point decimal, which only consists. And there is an error in your line 10 -
bet = bettingentry.get()
Bettingentry isn't defined anywhere. And, I don't think so its a module
bettingentry is defined on line 25 - remember LEGB.

Having another quick skim through the code: is line 30 the problem? Did you intend to call the function there, passing Its return value as command, or should you be passing the function itself? It's an educated guess - I assume that the function passed as command is called when the button is pressed. Drop the parens if you did mean to pass the function. I suspect the same is true for line 33.

The docs at effbot.org seem to confirm my suspicion (note that bind is inherited from the Widget class, so also see its docs).