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

Gtk#(MonoDev环境):点击按钮获取Entry文本并显示到Label

Gtk# 千克与磅单位转换GUI应用修改方案

当前在MonoDevelop中使用Gtk#开发重量单位转换工具,需要修改Convert按钮的点击事件,实现从Entry组件获取输入文本并显示到Label组件中(当前按钮仅执行关闭程序操作)。

界面截图

重量单位转换GUI界面

修改后的代码实现

using System;
using Gtk;

public partial class MainWindow : Gtk.Window
{
    public MainWindow() : base(Gtk.WindowType.Toplevel)
    {
        Build();
    }

    protected void OnDeleteEvent(object sender, DeleteEventArgs a)
    {
        Application.Quit();
        a.RetVal = true;
    }

    // Convert button 点击事件
    protected void OnButton3Clicked(object sender, EventArgs e)
    {
        // 替换为你界面中实际的Entry控件名称(比如entryKilogram/entryPound)
        string inputContent = entryWeight.Text;

        // 输入有效性验证
        if (!string.IsNullOrWhiteSpace(inputContent) && double.TryParse(inputContent, out double weight))
        {
            // 替换为你界面中实际的Label控件名称(比如labelResult)
            // 先演示显示输入内容,后续可添加单位转换逻辑
            labelResult.Text = $"输入值:{inputContent}";
        }
        else
        {
            labelResult.Text = "请输入有效的数字!";
        }
    }
}

关键说明

  1. 控件名称替换:代码中的entryWeight和labelResult必须和你在Gtk设计器中设置的Entry、Label控件的Name属性一致,否则会报错。
  2. 输入验证:通过double.TryParse避免无效输入导致的程序异常,提升稳定性。
  3. 后续扩展:若要实现单位转换,可在验证通过后添加计算逻辑:
    • 千克转磅:double pound = weight * 2.20462;
    • 磅转千克:double kilogram = weight / 2.20462;
      之后将计算结果赋值给Label即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:34:57