Home > database >  Creat and access dictionary within class
Creat and access dictionary within class

Time:10-04

I have created a class within tkinter that builds a frame and buttons (example below).

I am also trying to create a series of radiobuttons each with a command, and rather than having to type three times the same, I am trying to use a dictionary that stores the function name and the function (again see below):

import tkinter as tk
from tkinter import ttk
from tkinter import *

class EnoxDoseCalculator:    
    def __init__(self, root):
       root.title('Enoxaparin Dose Calculator')
       indication = {'VTE': self.vte,  'Atrial Fibrilation': self.af, 'Mechanical Heart valve': self.mech}
    
       mainframe = ttk.Frame(root)
       mainframe.grid(column = 0, row = 0, sticky='nsew')
       test_button = ttk.Button(mainframe, text= 'Push Mew!!', command = self.format)
       test_button.grid(row = 0, column = 0)

   def vte(self):
       pass

   def af(self):
       pass
       
   def mech(self):
       pass

   def format(self):
       self.var3 = tk.StringVar()
       for key, value in self.indication.items():
           ttk.Radiobutton(mainframe, text = self.indication.key, variable = self.var3, value = self.indication.key, command = self.indication.value).grid(row = n 1, column =0, sticky = 'nswe')

root = Tk()
EnoxDoseCalculator(root)
print(dir(EnoxDoseCalculator))

root.mainloop()

However, I keep getting this message: I get this is to do with the dictionary functions being listed before they are created, so my question is, where do I place said dictionary, because I am sure this is possible. or is it that I am using the wrong names for the function?

CodePudding user response:

Try this:

class EnoxDoseCalculator:    
    def __init__(self, root):
       self.root = root  # add this (mostly for consistency/best practice)
       self.root.title('Enoxaparin Dose Calculator')
       self.indication = {'VTE': self.vte,  'Atrial Fibrilation': self.af, 'Mechanical Heart valve': self.mech}
    
       self.mainframe = ttk.Frame(self.root)  # update this to include 'self'
       self.mainframe.grid(column=0, row=0, sticky='nsew')
       # update this to include 'self'
       self.test_button = ttk.Button(self.mainframe, text='Push Mew!!', command=self.format)
       self.test_button.grid(row=0, column=0)

Using self to namespace your class variables to EnoxDoseCalculator

  • Related