【问题标题】:Retrieving attribute from checkbuttons - Tkinter, checkbuttons, python从检查按钮检索属性 - Tkinter、检查按钮、python
【发布时间】:2021-08-14 03:22:15
【问题描述】:

我正在尝试制作一个待办事项程序。每个Task 都有一些属性,其中一个是基于某些用户输入的。 当您添加 新任务 时,有一个选项可以检查新任务可能与之相关的所有现有任务(例如,新任务可能是洗碗,而现有任务之一是为它买肥皂——所以它们有某种联系)。

如果它澄清了什么,这是一张图片:

假设我检查了 3 个框/现有任务。 我想检索与每个选中的任务按钮关联的每个值属性(代码中的val_var)。然后,所有检查的任务值的总和将成为当前添加的新任务的属性 connectivity

但是,我不确定如何“获取”已检查按钮的所有检查按钮值,即使这很可能是一个微不足道的问题。

简化代码:

from tkinter import Tk, Frame, Button, Entry, Label, Canvas, OptionMenu, Toplevel, Checkbutton
import tkinter.messagebox 


task_list = []
task_types = ['Sparetime', 'School', 'Work']

class Task:
    def __init__(self, n, h, v,):
        self.name = n
        self.hours = h
        self.value = v
        #self.connectivity = c


def show_tasks():
    task = task_list[-1]

    print('\n')
    print('Value:')
    print(task.value)


def open_add_task():
    taskwin = Toplevel(root)
    taskwin.focus_force()
    
    #Name
    titlelabel = Label(taskwin, text='Title task concisely:', font=('Roboto',11,'bold')).grid(column=1, row=0)
    name_entry = Entry(taskwin, width=40, justify='center')
    name_entry.grid(column=1, row=1)

    #HOURS(required)
    hourlabel = Label(taskwin, text='Whole hours \n required', font=('Roboto',10)).grid(column=1, row=16)
    hour_entry = Entry(taskwin, width=4, justify='center')
    hour_entry.grid(column=1, row=17)

    #CONNECTIVITY
    C_lab = Label(taskwin,text="Check tasks this task is related to").grid(column=1, row=18)
    placement=19
    for task in task_list:
        Checkbutton(taskwin, text=(task.name)).grid(column=1, row=placement, sticky="w")
        placement+=1

    def add_task():
        if name_entry.get() != '': 

            val_var = (int(hour_entry.get())/10)
                
            task_list.append(Task(name_entry.get(), hour_entry.get(), val_var))
            show_tasks()
            listbox_tasks.insert(tkinter.END, name_entry.get())
            name_entry.delete(0, tkinter.END)
            taskwin.destroy()
        else:
            tkinter.messagebox.showwarning(title='Whoops', message='You must enter a task')

        
    Add_button = Button(taskwin, text='Add', font=('Roboto',10), command=add_task).grid(column=2, row=placement, sticky="e")
    placement+=1
    

root = Tk()

task_frame = Frame()
# Create UI
your_tasks_label = Label(root, text='THESE ARE YOUR TASKS:', font=('Roboto',10, 'bold'), justify='center')
your_tasks_label.pack()

listbox_tasks = tkinter.Listbox(root, height=10, width=50, font=('Roboto',10), justify='center')
listbox_tasks.pack()

#BUTTONS
New_Task_Button = Button(root, text='New Task', width=42, command=open_add_task)
New_Task_Button.pack()

root.mainloop()

【问题讨论】:

  • 如果您将代码缩减为 minimal reproducible example,将会有所帮助。如果问题是关于从复选框列表中获取值,我们不需要任何与任务相关的代码。尝试使用框架、复选按钮和多一点代码来简化您的问题。
  • 谢谢。我很抱歉。我现在已经编辑并简化了它

标签: python python-3.x class tkinter tkinter.checkbutton


【解决方案1】:

您可以使用列表来保存 tkinter DoubleVar,该列表在每个任务的 Checkbutton 中使用,其 value 作为 onvalue 选项。然后你可以将DoubleVar列表中的所有值相加得到connectivity

以下是根据您的代码修改的示例:

from tkinter import Tk, Frame, Button, Entry, Label, Canvas, OptionMenu, Toplevel, Checkbutton, DoubleVar
import tkinter.messagebox


task_list = []
task_types = ['Sparetime', 'School', 'Work']

class Task:
    def __init__(self, n, h, v, c): # enable the "connectivity"
        self.name = n
        self.hours = h
        self.value = v
        self.connectivity = c

    # added to show the task details
    def __str__(self):
        return f"{self.name}: hours={self.hours}, value={self.value}, connectivity={self.connectivity}"


def show_tasks():
    task = task_list[-1]
    print(task)  # show the task details


def open_add_task():
    taskwin = Toplevel(root)
    taskwin.focus_force()

    #Name
    titlelabel = Label(taskwin, text='Title task concisely:', font=('Roboto',11,'bold')).grid(column=1, row=0)
    name_entry = Entry(taskwin, width=40, justify='center')
    name_entry.grid(column=1, row=1)

    #HOURS(required)
    hourlabel = Label(taskwin, text='Whole hours \n required', font=('Roboto',10)).grid(column=1, row=16)
    hour_entry = Entry(taskwin, width=4, justify='center')
    hour_entry.grid(column=1, row=17)

    #CONNECTIVITY
    C_lab = Label(taskwin,text="Check tasks this task is related to").grid(column=1, row=18)
    placement=19
    vars = [] # list to hold the DoubleVar used by Checkbutton
    for task in task_list:
        # add a DoubleVar to the list
        vars.append(DoubleVar())
        # use the task.value as the "onvalue" option
        Checkbutton(taskwin, text=task.name, variable=vars[-1], onvalue=task.value, offvalue=0).grid(column=1, row=placement, sticky="w")
        placement+=1

    def add_task():
        if name_entry.get() != '':

            val_var = (int(hour_entry.get())/10)
            # calculate the "connectivity" of the new task
            connectivity = sum(v.get() for v in vars)

            task_list.append(Task(name_entry.get(), hour_entry.get(), val_var, connectivity))
            show_tasks()
            listbox_tasks.insert(tkinter.END, name_entry.get())
            name_entry.delete(0, tkinter.END)
            taskwin.destroy()
        else:
            tkinter.messagebox.showwarning(title='Whoops', message='You must enter a task')


    Add_button = Button(taskwin, text='Add', font=('Roboto',10), command=add_task).grid(column=2, row=placement, sticky="e")
    placement+=1


root = Tk()

task_frame = Frame()
# Create UI
your_tasks_label = Label(root, text='THESE ARE YOUR TASKS:', font=('Roboto',10, 'bold'), justify='center')
your_tasks_label.pack()

listbox_tasks = tkinter.Listbox(root, height=10, width=50, font=('Roboto',10), justify='center')
listbox_tasks.pack()

#BUTTONS
New_Task_Button = Button(root, text='New Task', width=42, command=open_add_task)
New_Task_Button.pack()

root.mainloop()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-16
    • 1970-01-01
    • 2020-11-22
    • 1970-01-01
    • 2017-03-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多