0

Is this written technically ok? Will it cause any problems. I cannot find any info about this way of constructing code for tkinter, however it works..

myButton = tkinter.Button(main_window)
myButton['text'] = "Click Me!"
myButton['state'] = "normal"
myButton['command'] = myClick
myButton['fg'] = "blue"

instead of:

myButton = tkinter.Button(main_window,text="Click Me!",state="normal", command=myClick,fg="blue")

If someone think why, just because code looks neater to me.

Traper279
  • 43
  • 4

3 Answers3

0

What you have written will work but if your don't like the presentation of the standard syntax, you could always do something like this:

myButton = tkinter.Button(main_window,
                      text="Click Me!",
                      state="normal",
                      command=myClick,
                      fg="blue")
TheFluffDragon9
  • 514
  • 5
  • 11
0

According to the docs it is a legitim way to configure your widgets.

The reason why this works is because of the mapping protocol that is used by tkinter. As an example you can see here how it works and there is no danger in usage of it:

class Unpackable(object):
    def __init__(self):
        self.options=['hello','world']
    def keys(self):
        return self.options
    def __getitem__(self, key):
        return dict(zip(self.options,'first_word last_word'.split()))[key]
    
unp = Unpackable()
print(unp['hello'])

Output:

first_word

The offical python documentation says to setting options:

Options control things like the color and border width of a widget. Options can be set in three ways:

At object creation time, using keyword arguments

fred = Button(self, fg="red", bg="blue")

After object creation, treating the option name like a dictionary index

fred["fg"] = "red"
fred["bg"] = "blue"

Use the config() method to update multiple attrs subsequent to object creation

fred.config(fg="red", bg="blue")
Thingamabobs
  • 7,274
  • 5
  • 21
  • 54
0

This is correct.i mean to say you have just defined variable of button then you are adding attributes of button In following way all attributes are called in one statement only. myButton = tkinter.Button(main_window,text="Click Me!",state="normal",command=myClick,fg="blue")

But you have called all attributes by variable.it just take more Lines.

And technically what you have written is fine

Vishal Pandey
  • 349
  • 1
  • 4
  • 15
  • How it would be then: myButton.text="examplestring" ??? Seems to not working. – Traper279 Nov 29 '20 at 16:50
  • Actually that was my fault myButton.(attributes) work for pack() place() and greed() not any other . What you did is mostly use to design a window – Vishal Pandey Nov 29 '20 at 19:18