所以我一直在研究一个项目,最近我的检查按钮遇到了问题。每当我尝试variablenname.get()
时,它就不会像int value has no attribute get()
那样工作。我确实也使用了variablename = IntVar()
,我想做的是使if语句依赖于checkbutton的值。
var = IntVar()
BTR = Tk()
Discounts = Checkbutton(BTR, text="Discount (Students, Under 18s, 65+ and Disability Badge Holders)", font = ("times", 30), bg="#252538", fg = "#99FFFF", variable = var)
Discounts.place(x=120, y=300)
PriceTag=Label(BTR, text =("£", Cost), font = ("times", 50), fg = "White", bg = "#252538")
PriceTag.place(x=1000, y= 450)
val=Label(BTR, text = Tickets, font = ("times", 22), height = 5, width = 15, bg= "White")
val.place(x=175, y=550)
add=Button(BTR, text = "+", font = ("times", 22), height = 5, width = 10, bg = "#B266FF", command = lambda: UpdateAdd(val, BTR, PriceTag, BusTicketPrice, price, var))
add.place(x=420, y=550)
def UpdateAdd(val, BTR, PriceTag, BusTicketPrice, price, var):
var = var.get()
Tickets = Tickets + 1
val.destroy()
val = Label(BTR, text = Tickets, font = ("times", 22), height = 5, width = 15, bg= "White")
val.place(x=175, y=550)
PriceTag.destroy()
if price == "Peak" and var == 0 :
BusTicketPrice=BusTicketPrice*1.25
elif var == 1 and price == "Peak":
BusTicketPrice=BusTicketPrice
elif var == 1 and price == "Off-Peak":
BusTicketPrice=BusTicketPrice*0.75
elif price == "Off-Peak" and var == 0):
BusTicketPrice=BusTicketPrice
Cost = BusTicketPrice * Tickets
Cost = round(Cost, 3)
PriceTag=Label(BTR, text =("£", str(Cost), "0"), font = ("times", 50), fg = "White", bg = "#252538")
PriceTag.place(x=1000, y= 450)
答案 0 :(得分:2)
此代码存在一些问题。首先,在创建根窗口并使用Tk()
调用启动Tcl解释器之前,不应尝试创建任何Tkinter对象,包括窗口小部件和IntVar。我很惊讶你的代码没有打印出像
AttributeError: 'NoneType' object has no attribute '_root'
因为您在var = IntVar()
之前有BTR = Tk()
。我没有尝试运行您发布的代码,因为它不是MCVE。
你的错误的主要原因是UpdateAdd
在函数开头附近var = var.get()
(从var
获取整数值然后将整数对象绑定到名称为var
},但稍后又有var.get()
,但由于现在var
引用了整数对象,而不是IntVar
,因此无法工作它最初是绑定的。
这是一个最小程序,它表明使用带有Checkbutton的IntVar可以按预期工作。
import tkinter as tk
BTR = tk.Tk()
var = tk.IntVar()
title = tk.Label(BTR, text="Purchase Bus or Tram Tickets")
title.pack()
discounts = tk.Checkbutton(BTR, text="Discount", variable=var)
discounts.pack()
test = tk.Button(BTR, text="test", command=lambda: print(var.get()))
test.pack()
BTR.mainloop()
按"测试"按钮,Checkbutton的当前状态将打印到控制台。