tkinter:将多个功能分配给一个按钮

时间:2017-10-20 10:05:59

标签: python python-3.x tkinter

我正在尝试使用Tkinter构建罗马数字转换器。我需要使用一个按钮,如果输入数字,将小数转换为罗马数字,如果输入数字,则将罗马数字转换为小数。如何将这两个功能分配给一个按钮,并调用哪个功能对应于输入的内容?

这是我到目前为止所做的:

    from tkinter import *
    root = Tk()
    root.title('Roman numerals')
    root.geometry('400x300')

    numRomanMap = (('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))

    def roman_number():
        roman_string = ''
        n = float(eval(ent.get()))
        wrongValue = ('Number is out of range')
        if not 1 <= n <= 9999:
                    return wrongValue
        for numeral, integer in numRomanMap:
            while n >= integer:
                roman_string += numeral
                n -= integer
        print (roman_string)

    def decimal_number(s):
        dec_number = 0
        s = str(eval(ent.get()))
        index = []
        for i in range(len(s)):
            for numeral, integer in numRomanMap:
                if s[i] == numeral:
                    index.append(integer)
        index.append(0)
        for i in range(len(s)):
            if index[i] >= index[i+1]:
                dec_number = dec_number + index[i]
            else:
                dec_number = dec_number - index[i]
        print (dec_number)

    Convertb = Button(root, text='Convert', command = roman_number)
    ent = Entry(root)
    ent.pack()
    ent.delete(0, END)
    ent.insert(0, 'Enter a number')
    Convertb.pack()

    root.mainloop()

1 个答案:

答案 0 :(得分:1)

添加一个函数以查看输入是否为数字。

def check_input():
    s = ent.get()
    if (isinstance(s, int)):
        roman_number(s)
    else:
        decimal_number(s)

然后从按钮调用该功能:

Convertb = Button(root, text='Convert', command = check_input)