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

Tkinter按钮点击执行条件判断:年龄身高输入与结果输出问题

过山车乘坐资格判断程序解决方案

核心问题

刚接触Tkinter开发时,遇到两个关键卡点:

  • 无法实现按钮点击触发条件判断的逻辑
  • 不知道如何获取输入框(enterage和enterheight)中的用户输入数据

修改后的完整可运行代码

from tkinter import *

def check_ride():
    # 获取输入内容并处理类型转换,添加异常处理避免非数字输入崩溃
    try:
        age = int(enterage.get())
        height = int(enterheight.get())
        
        # 清空输出框原有内容
        output.delete(1.0, END)
        
        # 执行乘坐资格判断
        if age >= 12 and height >= 150:
            result = "You are ready to ride"
        else:
            result = "You are too short, young or both"
        
        # 将结果插入输出框
        output.insert(END, result)
    except ValueError:
        output.delete(1.0, END)
        output.insert(END, "请输入有效数字")

window = Tk()
window.title("Rollercoaster")

l0 = Label(window, text = "Can you ride the roller coaster?", bg="black", fg="white", font=("Times New Roman",14, "italic"))
l1 = Label(window, text = "Enter Age")
l2 = Label(window, text = "Enter Height")
l3 = Label(window, text = "Can you ride it?")

l0.grid(row = 0, column = 1, sticky = W, pady = 2)
l1.grid(row = 1, column = 0, sticky = W, pady = 2)
l2.grid(row = 2, column = 0, sticky = W, pady = 2)
l3.grid(row = 3, column = 0, sticky = W, pady = 2)

output = Text(window, width=20, height=1, wrap=WORD, background="white")
output.grid(row=4, column=0, columnspan=2, sticky=W)

enterage = Entry(window)
enterheight = Entry(window)

enterage.grid(row = 1, column = 1, pady = 2)
enterheight.grid(row = 2, column = 1, pady = 2)

# 绑定按钮点击事件到判断函数
b1 = Button(window, text = "Submit", command=check_ride)
b1.grid(row = 1, column = 2)

window.mainloop()

关键逻辑说明

  • 获取输入数据:通过enterage.get()和enterheight.get()提取输入框的文本内容,用int()转换为整数类型用于数值判断。
  • 按钮触发逻辑:给Button组件添加command=check_ride参数,点击按钮时自动执行check_ride函数。
  • 输出结果更新:每次判断前用output.delete(1.0, END)清空输出框旧内容,再通过output.insert(END, result)插入新判断结果。
  • 异常防护:用try-except捕获ValueError,当用户输入非数字内容时,提示输入有效数字,避免程序崩溃。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 12:26:01