You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python Tkinter如何调用带参函数及解决GUI货币计算器输入取值问题

问题核心原因
  • 你代码中FromG = FromE.get()、ToG = ToE.get()、AmoutG = AmoutE.get()是在输入框创建完成后立刻执行的,此时用户还没有进行任何输入操作,这三个变量存储的永远是空值,不是点击计算按钮时的实时输入内容。
  • 输入框get()返回的是字符串类型,金额需要转换为数值类型才能参与计算。
  • 你调用带参数函数的思路没有问题,只需要把参数获取的时机调整到点击按钮时即可。
Tkinter 按钮绑定带参数函数的通用方式

通常有两种实现方案:

  1. 使用lambda匿名函数包裹,你当前用的就是这个方案,只要保证参数是调用时实时取值即可:
# 正确写法:点击按钮调用函数时才实时获取输入
command=lambda: 你的函数名(参数1, 参数2, 参数3)
# 错误写法:创建按钮时就计算了参数值,后续不会更新
command=你的函数名(参数1, 参数2, 参数3)
  1. 使用functools.partial包装:
from functools import partial
command=partial(你的函数名, 参数1, 参数2, 参数3)
修改后的完整代码
import requests
import tkinter as tk
import json

url = ("https://bankofgeorgia.ge/api/currencies/getSpecialRates")

def convert(from_currency, to_currency, amount): 
    # 增加简单异常处理,避免输入错误导致程序崩溃
    try:
        amount = float(amount)
        #FORGEL
        if from_currency == "GEL":
            amount = amount / Rates[to_currency]
            amount = round(amount,2)
        elif to_currency == "GEL":
            amount = amount * Rates[from_currency]      
        #FORGEL
        else:    
            amount = amount / Rates[to_currency]
            amount = round(amount * Rates[from_currency], 2) 
        ss.configure(text=str(amount))
        return amount
    except:
        ss.configure(text="输入错误,请检查币种/金额格式")

Rates = {}

data= requests.get(url).json()
currencies = data['data']
for x in currencies:
    currency = x['currency']
    rateSell = x['rateSell']
    Rates.update({currency:rateSell})
    
window = tk.Tk()

FromL = tk.Label(text="From")
FromE = tk.Entry()

ToL = tk.Label(text="To")
ToE = tk.Entry()

AmoutL = tk.Label(text="Amount")
AmoutE = tk.Entry()

ss = tk.Label(text="0")
# 点击按钮时才实时获取输入框内容作为参数
widget = tk.Button(window, text="Calculate", command=lambda:convert(FromE.get().strip(), ToE.get().strip(), AmoutE.get().strip()))

FromL.pack()
FromE.pack()
ToL.pack()
ToE.pack()
AmoutL.pack()
AmoutE.pack()
ss.pack()
widget.pack()

window.mainloop()

内容的提问来源于stack exchange,提问作者George

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 20:30:05