我正在尝试制作一个程序来判断某个人的年龄是否为吸烟年龄。我能够使其在命令行中工作,但我决定制作一个实际的窗口程序。 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:
循环,特别是因为您永远不会打破
它:
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.')
....
关于python - 我的 tkinter 窗口立即关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34193613/