我正在尝试制作一个程序来判断给定人的年龄是否为吸烟年龄。我能够让它在命令行中工作,但我决定我想制作一个实际的窗口程序。 http://pastebin.com/0HettMLx是我当前的代码。
import random
import sys
import os
import time
import tkinter
from tkinter import messagebox, Label, Button, StringVar
age=StringVar
window = tkinter. Tk()#creates a new window
window.title("Are you old enough to smoke?")#title
window.geometry("300x200")#window size
window.wm_iconbitmap('favicon.ico')#icon
photo=tkinter.PhotoImage(file="images.png")#picture in said window
w=tkinter.Label(window, image=photo)
w.pack()
lbl=tkinter.Label(window, text="Please enter your age.", bg="light salmon", fg="blue2")#label text & color
lbl.pack()
ent=tkinter.Entry(window, text="(Your age here)", textvariable=age)
ent.pack()
def callback():
button_pressed=True
while True:
if (age) >= 18:
print('You are legally able to smoke.')
else:
print("You are not of legal age to smoke.")
if (age)>= 18:
print ("You are legally able to smoke cigarettes.")
if (age)>=21:
print("You are legally able to smoke marijuana.")
if (age)>=40:
print("You're above the age of forty,\nDo you really need to ask if you're old enough?")
if (age)<=12:
print("You're to young to smoke get out of here.")
btn=tkinter.Button(window, text="Confirm", bg="sienna1", fg="blue2", relief="groove", command=callback())
btn.pack()
window.configure(background='light salmon')#back ground
window.mainloop()# draws window
但每次我去运行它时,窗口打开但立即关闭。它只显示按钮、标签和条目就可以正常工作,但是一旦我开始尝试将 command=callback 实现到按钮中,它就不起作用了。我只想知道如何解决它关闭问题。
运行python34,win7-64位。
请您参考如下方法:
当您将回调分配给按钮时,您需要分配可调用对象。 command=callback() 将 callback() 返回的内容(None)分配给命令,而不是设置 command=callback:
btn=tkinter.Button(window, text="Confirm", bg="sienna1", fg="blue2", relief="groove", command=callback)
您的程序可能会崩溃,因为您正试图通过像普通变量一样简单地引用它来访问 age,StringVars 有点不同。要获取 StringVar 的值,您需要对其调用 get()。您还需要使用 StringVar() 而不仅仅是 StringVar 正确初始化 StringVar。您还需要在调用 Tk() 之后执行此操作:
window = tkinter.Tk() # creates a new window
age = StringVar() # you need to call this after the line above
最后,在您的回调中,您需要正确访问 StringVar 的值并将其转换为整数,这在回调顶部最简单,方法是定义一个新变量来保存整数,然后替换 年龄。也没有必要在这个回调中有一个 while True: 循环,特别是因为你永远不会 break :
def callback():
ageint = int(age.get())
button_pressed=True
# Remove while True: loop and fix indentation below
if (ageint) >= 18: # Replace all "age" with "ageint" from here on
print('You are legally able to smoke.')
....
