PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, November 8, 2022

[FIXED] How do I create a menu in tkinter using a for loop?

 November 08, 2022     menu, python, tkinter     No comments   

Issue

I want to create a menu in tkinter that lists names from a csv file. I am using a lambda function, but I cannot figure out how to make the buttons do different things. They all do the same thing as the last one since it was the last one created. Here is some code to demonstrate:

from tkinter import *

def printindex(x):
    print(x)

root = Tk()

menu = Menu(root)

file = Menu(menu)

for i in range(10):
    file.add_command(label=str(i), command=lambda: printindex(i))

menu.add_cascade(label="File", menu=file)

root.config(menu=menu)

root.mainloop()

When I run this, all of the options in the menu print 9.

I want all the items in the menu to point to the same function but pass in their respective values. How would I do this?


Solution

The values of variables used in closures are looked up when the function is called, and in your case the value of i is 9. You can modify your lambda function to force a closure:

command=lambda i=i: printindex(i)


Answered By - Henry Yik
Answer Checked By - Senaida (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing