【问题标题】:I can't make a function for this button我无法为此按钮创建功能
【发布时间】:2021-02-01 09:22:31
【问题描述】:

我正在用python编写一个程序来计算你的出生年份,一切正常,但是当我开始制作图形部分时,它开始变得越来越难,我无法让按钮打印出这句话告诉用户名他们出生的年份。

from tkinter import *
import datetime

root = Tk()


def myClick():
    sentence_label=Label(root, text= sentece)

today = datetime.date.today()
name = input("Enter your name: ")


age = Entry(root, width=25, bg="white", fg="black", text= "Enter your age: ")
name = Entry(root, width=25, bg="white", fg="black", text="Enter your name: ")
birthday = Entry(root, width=25, bg="white", fg="black",text="Enter your birthday: ")

age.pack(padx=0, pady=1)
name.pack(padx=2, pady=1)
birthday.pack(padx=2, pady=2) 


age_label = Label(root, text="Enter your age: ")
name_label = Label(root,text="Enter you name: ")
birthday_label = Label(root, text="Enter you birthday in dd/mm: ")

age_label.pack(padx=0, pady=0)
name_label.pack(padx=1, pady=0)
birthday_label.pack(padx=2, pady=0)
myButton = Button(root, text="Click when done")
myButton.pack(padx=3 , pady=3 )

while True:
 try:
    age = int(input("Enter your age: "))
    break
 except ValueError:
    print("Invalid age, try again")
while True:
 try:
    birthday = (input("Enter your birthday in dd/mm format: "))
    birthday_day, birthday_month = birthday.split("/")
    birthday_day = int(birthday_day)
    birthday_month = int(birthday_month)
    if birthday_day>31 or birthday_day<1 or birthday_month>12 or birthday_month<1:
        print("Invalid birthday, try again")  
    else:
        break 
 except ValueError:
     print("Invalid birthday, try again")

if birthday_month<today.month and birthday_day<today.day: 
    sentence= print("Hello ", name,"you are ", age, "years old. You were born in ", today.year - age,".")
elif birthday_month == today.month and birthday_day == today.day:
    sentence= print("Happy birthday",name, "you are", age, "years old. You were born in", today.year - age,".")
else:
    sentece=print ("Hello",name,"you are ", age, "years old. You were born in ", today.year - 1 - age)

root.mainloop()

【问题讨论】:

  • 这是一个字符串。还有,问题是什么?你实际上还没有说困难是什么。乍一看,我看到您正在尝试通过打印分配给sentence,打印不返回任何内容,因此当它打印到屏幕时,sentence 将为空
  • 我之前没用过tkinter,所以不太懂。在我开始做图形部分之前,代码按我的意愿工作。我想输入年龄、姓名和生日,当我按下按钮时,它会说“句子”。
  • 看看here如何使用按钮,看看底部的例子,它几乎可以满足你的需求,按下按钮并弹出一个消息框
  • 我已经解决了这个问题,但还是谢谢你。

标签: python python-3.x tkinter


【解决方案1】:

你为什么要这样做 sentence = print('bla bla')?

您希望它在哪里打印?

您应该直接更新sentence_label 的值而不使用打印语句。

我从未使用过 tkinter,但仍然尝试一下:-

sentence_label.config(text = "your output text here")

你应该从 gui 而不是从控制台获取年龄和姓名值!否则gui是没用的。

您的代码中有很多错误。您应该使用 linter 检查所有错误

【讨论】:

  • 我实际上已经解决了问题,但还是谢谢你。