我正在尝试编写一个程序,该程序可以告诉某个人的年龄是否为吸烟年龄。我能够使其在命令行中工作,但是我决定要制作一个实际的窗口程序。 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-64bit。

最佳答案

将回调分配给按钮时,需要分配可调用对象。 command=callback()为命令分配callback()返回(None)的内容,而是设置command=callback

btn=tkinter.Button(window, text="Confirm", bg="sienna1", fg="blue2", relief="groove", command=callback)


您的程序可能崩溃,因为您尝试通过像普通变量一样简单地引用age来访问get(),StringVars有所不同。要获取StringVar的值,您需要在其上调用StringVar()。您还需要使用StringVar而不是Tk()正确初始化StringVar。您还需要在调用age之后执行此操作:

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.')
    ....

10-06 12:28