TKinter проблема с получением значения радиокнопки

1

У меня есть определенная функция, которая содержит 4 радиообмена, которые содержат ответы на случайно заданные вопросы, и у меня есть другая функция, которая проверяет правильность ответа выбранного радиообмена, и если да, добавьте 1 переменную "оценка", однако, переменная счета не увеличивается правильно и, кажется, обновляется случайным образом:

def answers():
    global text, rb1, rb2, rb3, rb4, v

    v = int() 

    rb1 = Radiobutton(root, text="One", variable=v, value=1, bg = "white", font = ("Segoe UI", 11))
    rb1.place(x=20, y=80)

    rb2 = Radiobutton(root, text="Two", variable=v, value=2, bg = "white", font = ("Segoe UI", 11))
    rb2.place(x=20, y=120)

    rb3 = Radiobutton(root, text="Three", variable=v, value=3, bg = "white", font = ("Segoe UI", 11))
    rb3.place(x=20, y=160)

    rb4 = Radiobutton(root, text="Four", variable=v, value=4, bg = "white", font = ("Segoe UI", 11))
    rb4.place(x=20, y=200)

    next() 





def next():   
    val=(int(v))

    if question_variable == "Describe what the instruction 'BRP' does.":
        rb1['text'] = "If the contents of the accumulator are zero or positive, set the program counter to address xx."
        rb2['text'] = "If the contents of the accumulator are zero only, set the program counter to address xx."
        rb3['text'] = "If the contents of the accumulator are positive only, set the program counter to address xx."
        rb4['text'] = "If the accumulator is empty, set the program counter to address xx."
        if val == 1: 
            score += 1


    elif question_variable == "Describe what is meant by the term 'Open Source Software'.":
        rb1['text'] = "Open source software is software that is paid-for only."
        rb2['text'] = "Open source software is software that is free."
        rb3['text'] = "Open source software is software with source code that anyone can inspect, modify, and enhance."
        rb4['text'] = "Open source software is copyrighted software."
        if val == 3:
            score += 1

    elif question_variable == "What is meant by the term 'Lossy Compression'?":
        rb1['text'] = "Lossy compression is a compression method that removes metadata from the file, resulting in smaller file sizes."
        rb2['text'] = "Lossy compression is a compression method that works by removing redundant and unrequired data."
        rb3['text'] = "Lossy compression is a compression method which reduces the file size without any noticeable quality loss."
        rb4['text'] = "Lossy compression is a risky compression method which could result in data corruption if used incorrectly."     
        if val == 2:
            score += 1

    elif question_variable == "What is the number '55' as an 8-bit unsigned binary integer?":
        rb1['text'] = "00110111"
        rb2['text'] = "11101100"
        rb3['text'] = "11001011"
        rb4['text'] = "00110100"
        if val == 1:
            score += 1

    elif question_variable == "What might a printer use RAM for?":
        rb1['text'] = "To store its OS."
        rb2['text'] = "To store most frequently printed pages."
        rb3['text'] = "To hold the current and subsequent jobs."
        rb4['text'] = "To take RAM load off the main computer."
        if val == 3:
            score += 1

    elif question_variable == "Describe the term 'firewall'.":
        rb1['text'] = "A firewall prevents harmful software from accessing a computer."
        rb2['text'] = "A firewall redirects data packets via other nodes before reach its designated computer."
        rb3['text'] = "A firewall limits the speed that the packets are able to travel at."
        rb4['text'] = "A firewall enforces a set of rules about what data packets will be allowed to enter or leave a network."
        if val == 4:
            score += 1

    else:
        rb1['text'] = "Memory Address Register"
        rb2['text'] = "Arithmetic Logic Unit"
        rb3['text'] = "Memory Data Register"
        rb4['text'] = "Accumulator"
        if val == 4:
            score += 1

Может ли кто-нибудь определить, где я ошибаюсь?

  • 0
    Почему вы определили две функции с одинаковым именем?
  • 0
    @KarimNGorjux прости мой плохой. Исправил это
Теги:
tkinter

2 ответа

1

Поскольку v - глобальная переменная, вам не следует представлять ее как другую переменную в операторах if, которые определяют, какая кнопка нажата. Кроме того, v уже и целое число, поэтому вам не нужно использовать функцию int() в val

  • 0
    Спасибо за комментарий. Даже после устранения вышеуказанных проблем, проблема все еще сохраняется. Например, при запросе «Опишите, что подразумевается под термином« ПО с открытым исходным кодом ».», Даже после выбора 3-й радиокнопки, которая является правильной, оценка все равно не увеличивается.
  • 0
    Когда вы говорите, что он не увеличивается правильно, означает ли это, что он никогда не увеличивается или иногда увеличивается?
Показать ещё 2 комментария
1

Вы не можете использовать обычную переменную python для параметра variable. Поскольку вы используете целочисленные значения, это должен быть экземпляр IntVar. Чтобы получить значение, вам нужно вызвать метод get() в этом экземпляре.

  • 0
    Даже после того, как это было реализовано, и это система, которая у меня была до того, как я решил отказаться от нее, она все равно не работает и, кажется, увеличивает балл почти случайно
  • 0
    @FirasHafiz: когда я заменяю v=int() на v=IntVar() и заменяю val=(int(v)) на val=v.get() , а затем добавляю недостающий код, ваши радиокнопки работают нормально.
Показать ещё 1 комментарий

Ещё вопросы

Сообщество Overcoder
Наверх
Меню