簡體   English   中英

使tkinter輸入框值成為浮點數(python)

[英]making tkinter entry box value into a float (python)

我是初學者。 我已經盡力使下面的代碼將數字輸入帶入輸入框並使用它們進行計算。 我收到ValueError,但我沒有做任何事情來停止這種情況。 這應該是一個計算每月利息支付和總支出的程序。 在解決這個更基本的問題之前,我一直將其保持在簡單的產品上。 謝謝。

def multiply(var1, var2, var3):
    product = float(var1 * var2 * var3)
    return product


def btnClick(event):
    x = float(entry.get())


main = Tk()
main.title("Assignment 16")

main.geometry("500x500")
main["bg"] = "#000066"

lblFirst = Label(main, text="Amount to Pay: ")
lblFirst.grid(row=0, column=3, pady=5)
entry = Entry(main, width=20)
entry.grid(row=0, column=4)
amount = entry.get()
lblSecond = Label(main, text="Interest Rate (like 7.5): ")
lblSecond.grid(row=2, column=3, pady=10)
entry2 = Entry(main, width=20)
entry2.grid(row=2, column=4)
rate = entry2.get()
lblThird = Label(main, text="Years to Pay: ")
lblThird.grid(row=4, column=3, pady=15)
entry3 = Entry(main, width=20)
entry3.grid(row=4, column=4)
years = entry3.get()

try:
    # Try to make it a float
    if amount.isnumeric():
        amount = float(amount)

except ValueError:
    # Print this if the input cannot be made a float
    print("Bad input")

try:
    # Try to make it a float
    if rate.isnumeric():
        rate = float(rate)

except ValueError:
    # Print this if the input cannot be made a float
    print("Bad input")

try:
    # Try to make it a float
    if years.isnumeric():
        years = int(years)

except ValueError:
    # Print this if the input cannot be made a float
    print("Bad input")

lblFourth = Label(main, text="Monthly Payment: ")
lblFourth.grid(row=6, column=3, pady=15)
lblFourthTwo = Label(main, text="XXXXX")
lblFourthTwo.grid(row=6, column=4)
lblFifth = Label(main, text="Total of Paymenta: ")
lblFifth.grid(row=8, column=3, pady=15)
lblFifthTwo = Label(main, text="XXXXX")
lblFifthTwo.grid(row=8, column=4)

button1 = Button(main, text='Convert', width=10, command=btnClick)
button2 = Button(main, text='Calculate', width=10, command=multiply(amount, rate, years))
button1.grid(padx=20, pady=20)

main.mainloop()

您的所有代碼都 mainloop啟動之前運行。

使用GUI工具包(如tkinker)的程序是事件驅動的 您的代碼在主循環之前和之后的事件處理程序中的設置中運行。

您可以使用驗證來確保僅輸入數字。

下面的工作示例(適用於Python 3)。 這也說明了如何從事件處理程序的編輯框中獲取值,以及如何創建綜合事件來更新其他小部件。

import tkinter as tk
from tkinter import ttk

# Creating and placing the widgets
root = tk.Tk()
root.wm_title('floating point entry')
qedit = ttk.Entry(root, justify='right')
qedit.insert(0, '100')
qedit.grid(row=0, column=0, sticky='ew')
result = ttk.Label(root, text='100')
result.grid(row=1, column=0)
ttk.Button(root, text="Exit", command=root.quit).grid(row=2, column=0)


# Callback functions
def is_number(data):
    if data == '':
        return True
    try:
        float(data)
        print('value:', data)
    except ValueError:
        return False
    result.event_generate('<<UpdateNeeded>>', when='tail')
    return True


def do_update(event):
    w = event.widget
    number = float(qedit.get())
    w['text'] = '{}'.format(number)

# The following settings can only be done after both the
# widgets and callbacks have been created.
vcmd = root.register(is_number)
qedit['validate'] = 'key'
qedit['validatecommand'] = (vcmd, '%P')
result.bind('<<UpdateNeeded>>', do_update)

# Run the event loop.
root.mainloop()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM