จะรับสถานะของ Checkbutton เมื่อถูกเลือกได้อย่างไร

ฉันจะรับสถานะของ Checkbutton ใน python ได้อย่างไร ฉันมีสิ่งนี้:

def doSomething():

  if #code goes here, if checkbutton is selected
   ...

check = Checkbutton(window, text="Add both", onvalue = 1, offvalue = 0)
check.pack(side="right")

person IAM    schedule 27.05.2013    source แหล่งที่มา
comment
ตรวจสอบโพสต์นี้: stackoverflow.com/questions/4236910/getting-checkbutton -รัฐ/   -  person Meowi    schedule 03.08.2020


คำตอบ (1)


คุณต้องเชื่อมโยง Checkbox กับตัวแปร:

is_checked = IntVar()
check = Checkbutton(window, text="Add both", onvalue=1, offvalue=0, variable=is_checked)

จากนั้นใช้ทำการตรวจสอบของคุณเช่น:

if is_checked.get():
    # do something
person Jon Clements♦    schedule 27.05.2013
comment
ทำให้ฉันสับสนไปสองชั่วโมงเพราะคำตอบนี้หายไป .get() - person ArtOfWarfare; 29.09.2014
comment
จะเป็นอย่างไรถ้าคุณไม่ต้องการสร้างตัวแปรใหม่สำหรับช่องทำเครื่องหมายล่ะ - person Foggy Minded Greenhorn; 17.05.2020