Как правильно хранить переменные контрольной кнопки в списке, который будет идентифицирован в более поздней функции программы? - PullRequest
0 голосов
/ 07 марта 2019

Ниже приведена часть всей моей программы, с которой у меня проблемы. Проблема заключается в использовании контрольных кнопок Tkinter. Я пытаюсь создать программу, которая принимает список операций, выбранных пользователем, и в зависимости от количества «операторов» создает контрольные кнопки, которые можно проверить, чтобы определить, какие операции выполняются каким оператором, идентифицированным по статусу соответствующей контрольной кнопки. государство. Но, к сожалению, единственные ответы, которые я получаю, это коды ошибок, вызванные моим использованием IntVar (), я считаю,

Вот вывод кода ниже:

Tkinter.IntVar экземпляр в 0x000000000EE332C8

Желаемый вывод для этого изображения - это, по сути, то, что показано в приведенном ниже блок-цитате

Состояние переменной = 1, Op1, оператор # 1

import Tkinter
import Tkinter as tk
from Tkinter import *


class Application(tk.Frame):
    def __init__(self, master=None):
        self.createWidgets()

    def createWidgets(self):

        operator = int(6) #assigned for testing
        lookingFor = ['op1','op2','op3','op4'] #assigned for testing
        self.checkList = [] #creating an empty list to store Checkbox variables

        cx,cy=0,0
        for x in range(0, operator):  ##creating left Lables
            cy+=1
            cx+=1
            label = Label(root)
            labelName = 'Operator#'
            label["text"] = str(labelName)+str(cy)
            label.grid(row=cx+1,column=0)

        cx,cy=0,0
        for y in lookingFor:   ##creating top labels
            cy+=1
            label = Label(root)
            label["text"] = str(y)
            label.grid(row=cx+1,column=cy)

        cx,cy=0,0
        for y in range(0, operator):
            cx+=1
            for x in lookingFor: #creating checkboxes
                var = IntVar()
                c = Checkbutton(root, variable = var)
                cy+=1
                c.grid(row=cx+1,column=cy)
                self.checkList.append(var)

            cy=0

        self.button = Button(root)
        self.button["text"] = 'Done'
        self.button["command"] = self.states
        self.button.grid(row=0,column=0)

    def states(self):
        #This function should print out the state of each button
        #as well as its corresponding 'Op#' and 'operator#'
        #So the program can later decide which operations are performed
        #when the program passes through each operator
        print (self.checkList) 


root = tk.Tk()
app = Application(master=root)
root.attributes('-topmost', True)
x=10
y=5
root.geometry("+%d+%d" % (x, y))
root.mainloop()

1 Ответ

0 голосов
/ 07 марта 2019

Прежде всего, полученный вами вывод на печать не является кодом ошибки. Если вы печатаете объект IntVar напрямую, вы получаете такое значение, но если вы хотите напечатать значение, хранящееся в IntVar, вам нужно вызвать метод get().

Теперь, чтобы получить подробный формат вывода, как вы и просили, вы можете использовать список таких списков для каждого оператора.

class Application(Frame):
    def __init__(self, master=None):
        self.createWidgets()

    def createWidgets(self):

        operator = int(6) #assigned for testing
        lookingFor = ['op1','op2','op3','op4'] #assigned for testing
        self.checkList = [[] for idx in range(operator)] #creating an empty list of lists to store Checkbox variables

        cx,cy=0,0
        for x in range(0, operator):  ##creating left Lables
            cy+=1
            cx+=1
            label = Label(root)
            labelName = 'Operator#'
            label["text"] = str(labelName)+str(cy)
            label.grid(row=cx+1,column=0)

        cx,cy=0,0
        for y in lookingFor:   ##creating top labels
            cy+=1
            label = Label(root)
            label["text"] = str(y)
            label.grid(row=cx+1,column=cy)

        cx,cy=0,0
        for y in range(0, operator):
            cx+=1
            for x in lookingFor: #creating checkboxes
                var = IntVar()
                c = Checkbutton(root, variable = var)
                cy+=1
                c.grid(row=cx+1,column=cy)
                self.checkList[y].append(var)

            cy=0

        self.button = Button(root)
        self.button["text"] = 'Done'
        self.button["command"] = self.states
        self.button.grid(row=0,column=0)

    def states(self):
        #This function should print out the state of each button
        #as well as its corresponding 'Op#' and 'operator#'
        #So the program can later decide which operations are performed
        #when the program passes through each operator
        for i, lst in enumerate(self.checkList, 1):
            for j, op in enumerate(lst, 1):
                print("Variable status = {}, Op{}, operator#{}".format(op.get(), j, i))

Это печатает вывод как:

Variable status = 1, Op1, operator#1
Variable status = 0, Op2, operator#1
Variable status = 0, Op3, operator#1
Variable status = 0, Op4, operator#1
Variable status = 0, Op1, operator#2
Variable status = 1, Op2, operator#2
Variable status = 0, Op3, operator#2
Variable status = 0, Op4, operator#2
Variable status = 0, Op1, operator#3
Variable status = 0, Op2, operator#3
Variable status = 0, Op3, operator#3
Variable status = 1, Op4, operator#3
Variable status = 0, Op1, operator#4
Variable status = 0, Op2, operator#4
Variable status = 0, Op3, operator#4
Variable status = 1, Op4, operator#4
Variable status = 0, Op1, operator#5
Variable status = 0, Op2, operator#5
Variable status = 0, Op3, operator#5
Variable status = 0, Op4, operator#5
Variable status = 0, Op1, operator#6
Variable status = 1, Op2, operator#6
Variable status = 0, Op3, operator#6
Variable status = 0, Op4, operator#6
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...