将变量从组合框传递到被调用的函数

时间:2017-09-21 14:21:21

标签: python tkinter

我正在尝试将tkinter组合框中的变量传递给单击“运行”按钮时调用的函数。我对python相对较新,我尝试过的每个选项都会产生错误 - 主要是变量未定义。我相信这是因为我没有在正确的地方定义它。非常感谢任何帮助。

from tkinter import *
from tkinter import ttk
from URL_Generator import crawl_site

listFile = open('regions1.txt','r')

root = Tk()
root.configure()
varItems = StringVar(root, value='')

class MainWindow(Frame):
    def __init__(self,master = None):
        Frame.__init__(self,master)
        self.master = master
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """Create Window Layout"""
        self.label = Label(self, text="List Items").pack()
        self.itemCombo = ttk.Combobox(self, width = 16, textvariable = varItems)
        self.itemCombo.bind("<Return>", self.itemCombo_onEnter)
        self.itemCombo.bind('<<ComboboxSelected>>',self.itemCombo_onEnter)
        self.itemCombo['values'] = [l.strip() for l in listFile.readlines()]
        self.itemCombo.pack()
        self.blank = Label(self,text='').pack()

        """I want to pass the value selected in the combobox to the crawl_region() function when pushing Run"""

        self.RunButton = Button(self, text="Run",command = crawl_site.crawl_region(region))
        self.RunButton.pack()

    def itemCombo_onEnter(self,event):
        varItems.set(varItems.get().lower().strip())
        mytext = varItems.get().strip()
        vals = self.itemCombo.cget('values')
        self.itemCombo.select_range(0,END)
        print(mytext)
        region = mytext

        """I want to pass mytext to the function called when pushing Run"""

        if not vals:
            self.itemCombo.configure(values = (mytext,))
        elif mytext not in vals:
            with open('regions1.txt', 'w') as f:
                self.itemCombo.configure(values=vals + (mytext,))
                f.write("\n".join(vals + (mytext,)))
                f.close()
        return 'break'

app = MainWindow(root)
root.mainloop()

调用的示例函数(crawl_site.crawl_region()):

class crawl_site():
    def crawl_region(region):
        print('passed region '+ str(region))

立即返回传递的区域[],但是当我做出选择或按下“运行”按钮时没有任何反应。

1 个答案:

答案 0 :(得分:2)

尝试以下代码。 我创建了一个类属性self.mytext,它在输入组合按钮itemCombo_onEnter时设置。按下按钮时,将调用onRunButton功能。如果已设置self.mytext,则会以crawl_region为参数调用self.mytext函数。

from tkinter import *
from tkinter import ttk
from URL_Generator import crawl_site

listFile = open('regions1.txt','r')

root = Tk()
root.configure()
varItems = StringVar(root, value='')

class MainWindow(Frame):
    def __init__(self,master = None):
        Frame.__init__(self,master)
        self.master = master
        self.grid()
        self.create_widgets()

    def create_widgets(self):
        """Create Window Layout"""
        self.label = Label(self, text="List Items").pack()
        self.itemCombo = ttk.Combobox(self, width = 16, textvariable = varItems)
        self.itemCombo.bind("<Return>", self.itemCombo_onEnter)
        self.itemCombo.bind('<<ComboboxSelected>>',self.itemCombo_onEnter)
        self.itemCombo['values'] = [l.strip() for l in listFile.readlines()]
        self.itemCombo.pack()
        self.blank = Label(self,text='').pack()

        """I want to pass the value selected in the combobox to the crawl_region() function when pushing Run"""

        self.RunButton = Button(self, text="Run",command = self.onRunButton)
        self.RunButton.pack()

    def onRunButton(self):
        if self.mytext:
            crawl_site.crawl_region(self.mytext)        

    def itemCombo_onEnter(self,event):
        varItems.set(varItems.get().lower().strip())
        mytext = varItems.get().strip()
        vals = self.itemCombo.cget('values')
        self.itemCombo.select_range(0,END)
        print(mytext)

        self.mytext = mytext
        """I want to pass mytext to the function called when pushing Run"""

        if not vals:
            self.itemCombo.configure(values = (mytext,))
        elif mytext not in vals:
            with open('regions1.txt', 'w') as f:
                self.itemCombo.configure(values=vals + (mytext,))
                f.write("\n".join(vals + (mytext,)))
                f.close()
        return 'break'

app = MainWindow(root)
root.mainloop()

由于此行

,您的代码无法正常工作
self.RunButton = Button(self, text="Run",command = crawl_site.crawl_region(region))

这会立即以区域作为参数调用方法crawl_region,并尝试将按钮的回调设置为该方法的结果。

另一种解决问题的方法。你没有创建另一个函数的问题就是使用lambda,但我认为我的方法更具可读性。