Přidat otázku mezi oblíbenéZasílat nové odpovědi e-mailemVyřešeno Python Tkinter - nefunguje .get() u Entry

Ahoj všichni! Začínám s Pythonem a chtěl jsem si zkusit napsat prográmek, kde uživatel spočítá součet (sčítance se pak budou generovat náhodně) a program mu ověří, jestli jej spočítal dobře. Narazil jsem ale na problém, že proměnná inp, do které jsem chtěl uložit hodnotu z Entry, prostě žádný řetězec nepřebírá (16. a 17. řádek), netuším proč :-(

Budu vděčný za jakoukoliv radu, na netu jsem četl, našel jsem i kód úplně stejný jako můj, ale ten můj nejede :D

Moc díky, Katsu

#-*- coding: utf-8 -*-

import tkinter as Tki

# GUI
base=Tki.Tk()
base.option_add('*Font', 'Verdana 10')

# Promenne
a = 2
b = 3
su = a + b

# Funkce
def Overit():
if su == inp.get():
verdict.set("OK")
else:
verdict.set("Špatně")

# Prvni radek
Tki.Label(base, bd=5, text = a).grid(row=0, column=0)
Tki.Label(base, bd=5, text=u"+").grid(row=0, column=1)
Tki.Label(base, bd=5, text = b).grid(row=0, column=2)
Tki.Label(base, bd=5, text=u"=").grid(row=0, column=3)

inp = Tki.StringVar()
ent = Tki.Entry(base, bd=5, textvariable = inp)
ent.grid(row=0, column=4)

Tki.Button(base, bd=5, text=u"Ověřit", command = Overit).grid(row=0, column=5)

# Druhy radek
verdict = Tki.StringVar()
Tki.Label(base, bd=5, width=50, textvariable = verdict).grid(row=1, column=4)

Tki.mainloop()

Předmět Autor Datum
Nejde to jednoduse proto, ze ve funkci Overit porovnavas cislo s retezcem, nebot get() vraci retezec…
mountdoom 25.09.2013 18:58
mountdoom
Aa, já jsem blbec :D ... Moc díky ;-) P.s.: Zbytek samozřejmě ošetřím, šlo mi teď čistě o tohle. poslední
Katsushiro 25.09.2013 20:45
Katsushiro

Nejde to jednoduse proto, ze ve funkci Overit porovnavas cislo s retezcem, nebot get() vraci retezec (=text), ne cislo. Staci pak navratovou hodnotu get() prevest na int. Porad to ale neni osetrene proti chybam, napriklad pokud nezadam nic, program spadne nebo kdyz zadam pismeno, program spadne atd.

Jeste nechapu, proc jsi pouzil u "#prvni radek" tolik Labelu, kdyz staci jen jeden.

#-*- coding: utf-8 -*-

import Tkinter as Tki

# GUI
base=Tki.Tk()
base.option_add('*Font', 'Verdana 10')

# Promenne
a = 2
b = 3
su = a + b

# Funkce
def Overit():
    if su == int(inp.get()):
        verdict.set("OK")
    else:
        verdict.set("Špatně")

# Prvni radek
Text = Tki.Label(base, text="%i + %i = "%(a,b), bd=5)
Text.grid(row=0,column=0)

inp = Tki.StringVar()
ent = Tki.Entry(base, bd=5, textvariable = inp)
ent.grid(row=0, column=1)

Tki.Button(base, bd=5, text=u"Ověřit", command = Overit).grid(row=0, column=3)

# Druhy radek
verdict = Tki.StringVar()
Tki.Label(base, bd=5, width=50, textvariable = verdict).grid(row=1, column=0,columnspan=4)

Tki.mainloop()

Zpět do poradny Odpovědět na původní otázku Nahoru