[英]I Cant Get My Tkinter Checkbutton Variable Value Using .get()
所以我一直在做一個項目,最近遇到了我的復選按鈕的問題。 每當我嘗試執行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)
這段代碼有幾個問題。 首先,在創建根窗口並使用Tk()
調用啟動 Tcl 解釋器之前,您不應嘗試創建任何 Tkinter 對象,包括小部件和 IntVars。 我很驚訝您的代碼沒有打印類似的錯誤消息
AttributeError: 'NoneType' object has no attribute '_root'
因為你在BTR = Tk()
之前有var = IntVar()
BTR = Tk()
。 我沒有嘗試運行您發布的代碼,因為它不是MCVE 。
您的錯誤的主要原因是在UpdateAdd
您在函數開頭附近執行var = var.get()
(它從var
獲取整數值,然后將該整數對象綁定到名稱var
),但再進一步下來你有var.get()
,這將不起作用,因為現在var
指的是整數對象,而不是它最初綁定到的IntVar
。
這是一個最小的程序,它演示了將 IntVar 與 Checkbutton 一起使用確實按預期工作。
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 的當前狀態將打印到控制台。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.