-1

I am working on a roman numerals converter for a school project and I ran into some problems when I tried to program a simple GUI for it. It worked perfectly without the GUI but now it outputs only 0.

My code is:

from tkinter import *

def int_to_rim(x):
    try:
        rezultat = ""
        stevila = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
        simboli = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
        x = int(x)
        for i in range(len(stevila)):
            while x - stevila[i] >= 0:
                rezultat += simboli[i]
                x -= stevila[i]
        e1.configure(text=rezultat)
        return rezultat
    except:
        print("error")
        pass

def roman_to_int(x):
    try:
        x = x.upper()
        rezultat_list = []
        rezultat = 0
        slov = {"M": 1000, "CM": 900, "D": 500, "CD": 400,
                "C": 100, "XC": 90, "L": 50, "XL": 40,
                "X": 10, "IX": 9, "V": 5, "IV": 4,
                "I": 1}
        for i in range(len(x)):
            rezultat_list.append(slov[x[i]])
            rezultat += slov[x[i]]
        for i in (range(len(rezultat_list))):
            if i < len(rezultat_list) - 1:
                if rezultat_list[i + 1] > rezultat_list[i]:
                    rezultat -= 2 * rezultat_list[i]
        e2.configure(text=rezultat)
        return rezultat
    except:
        print("error")
        pass

root = Tk()
root.title("Pretvornik rimskih številk")

rimŠt = StringVar()
intŠt = StringVar()

e1 = Entry(root)
e1.grid(row=1, column=1)
e2 = Entry(root)
e2.grid(row=2, column=1)

pretvoriRimsko = Button(root, text="Pretvori", command=lambda: roman_to_int(rimŠt.get()))
pretvoriRimsko.grid(row=1, column=2)
pretvoriArabsko = Button(root, text="Pretvori", command=lambda: int_to_rim(intŠt.get()))
pretvoriArabsko.grid(row=2, column=2)

l1 = Label(root, text="Rimska številka")
l1.grid(row=1, column=0)
l2 = Label(root, text="Arabska številka")
l2.grid(row=2, column=0)

root.mainloop()


# print(roman_to_int(input("Rim št.:")))
# print(int_to_rim(input("št.:")))

If I input a number directly into my function it works fine but if I input it through the UI it returns blank or 0.

Lafexlos
  • 7,618
  • 5
  • 38
  • 53

1 Answers1

0

You need to connect StringVar with the Entry. Right now they don't know each other.

rimŠt = StringVar()
intŠt = StringVar()

e1 = Entry(root, textvariable=rimŠt)
                 ^^ this one connects/associates each other
e1.grid(row=1, column=1)
e2 = Entry(root, textvariable=intŠt)
e2.grid(row=2, column=1)

By the way, you don't need StringVar in this code, you can directly get Entry contents with e1.get().

Lafexlos
  • 7,618
  • 5
  • 38
  • 53