简体   繁体   中英

issue with python Tkinter drop down menu

The following code is a program to append buttons onto an existing program so selection can occur on a more friendly interface rather than inside the code. I am trying to use drop down menu's but the setEthAnt1 function seems to have an error: TypeError: setEthAnt1() takes no arguments (1 given). I do not know what arg i am failing to pass in. Does anyone have any ideas?

from Tkinter import *
import ThreegroupsGraphics as three

def run():
    three.main()

def setEthAnt1():
    name = var.get()
    print name
    three.OneTo2Ant = name
    print three.OneTo2Ant

root = Tk()
var = StringVar()
var.set("Group 1 Ethnic Antagonism")
OptionMenu(root, var, "1","2","3","4","5","6","7","8","9","10", command = setEthAnt1).pack()
butn = Button(root, text = 'run',  command = run)
butn.pack()
root.mainloop() 

When you specify a command for an OptionMenu , the value of the selected item will be sent into the command, which essentially makes your var.get() unneeded. See below:

from Tkinter import *
import ThreegroupsGraphics as three

def run():
    three.main()

def setEthAnt1(name):
    print name
    three.OneTo2Ant = name
    print three.OneTo2Ant

root = Tk()
var = StringVar()
var.set("Group 1 Ethnic Antagonism")
OptionMenu(root, var, "1","2","3","4","5","6","7","8","9","10", command = setEthAnt1).pack()
butn = Button(root, text = 'run',  command = run)
butn.pack()
root.mainloop() 

If you don't want setEthAnt1 to have any parameters and still use var.get() , you can make the command for the OptionMenu a lamda function like so:

OptionMenu(root, var, "1","2","3","4","5","6","7","8","9","10", command = lambda _: setEthAnt1).pack()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM