John
John

Reputation: 43

Using variable to pass options to Tkinter widget

I am trying to make GUI with Tkinter, but I have occured a problem. My GUI is going to have a lot of very similar buttons with a lot of options (font, width, height, command etc.) and I would rather like to write name of variable, which store repeating options than repeat all commands over and over again.

I don´t even know if this possible. I tried save options as string in variable and then pass it into variable, but it raises: AttributeError: 'str' object has no attribute 'tk'

This is example of my buttons:

Num3 = Tk.Button(main, text="3", width = 2, height = 2, font = "Arial 16", command=lambda: nex("3")) Num4 = Tk.Button(main, text="4", width = 2, height = 2, font = "Arial 16", command=lambda: nex("4"))

And I would like that it look like this:

Var = 'main, width = 2, height = 2, font = "Arial 16",' Num3 = Tk.Button(Var, text="3",command=lambda: nex("3")) Num4 = Tk.Button(Var, text="4",command=lambda: nex("4"))

But it raises that AttributeError: 'str' object has no attribute 'tk'

Thanks for answers, people.

Upvotes: 1

Views: 449

Answers (1)

Mat.C
Mat.C

Reputation: 1439

Save them inside a dictionary, like this

import tkinter as tk

main = tk.Tk()

options = {"text": "Hello!", "font": "Arial 16", "width": 2, "height": 2}

Num4 = tk.Button(main, **options)
Num4.pack()

main.mainloop()

See this question How to pass dictionary items as function arguments in python?.

Upvotes: 1

Related Questions