使用Tkinter设置变量

时间:2015-05-26 14:58:00

标签: python python-2.7 tkinter

使用Tkinter进行bash - 我想要做的是一个运行系统调用功能的小GUI。

我希望能够使用GUI将v1,v2,v3设置为字符串项 - 它们用于“命令”功能。

def system_call( step_name, cmd ):
    try:
        subprocess.check_call(cmd, shell=True)

    except subprocess.CalledProcessError as scall:
        print "Script failed at %s stage - exit code was %s" % (step_name, scall.returncode)
        exit()


def command(v1, v2, v3):
    # Commandline string
    return v1 + " " + v2 + " " + v3

您将在下面找到界面设置。

# Create and name the window
        root = Tk()
        root.title("GUI - TEST VERSION")

        # Set the variables needed for function

        v1 = StringVar()
        v2 = StringVar()
        v3 = StringVar()

        # Make text entry box
        w = Label(root, text="V1")
        w.pack()
        text_entry = Entry(root, textvariable = v1.get())
        text_entry.pack()

        w = Label(root, text="V2")
        w.pack()
        text_entry = Entry(root, textvariable = v2.get())
        text_entry.pack()

        w = Label(root, text="V3")
        w.pack()
        text_entry = Entry(root, textvariable = v3.get())
        text_entry.pack()

        # Add a 'Run' button 
        b = Button(root, text="Run fuction", command= system_call(Command call, command(v1, v2,v3)))
        b.pack()

        # Call the GUI
        root.mainloop()

获取一个错误,指出无法捕获字符串对象和实例对象。

1 个答案:

答案 0 :(得分:4)

您以错误的方式使用变量。

在这里,您想要使用变量本身,而不是内容:

text_entry = Entry(root, textvariable=v1) # remove .get(), same for the other lines

在这里,您想要使用内容,而不是变量:

def command(v1, v2, v3):
    return v1.get() + " " + v2.get() + " " + v3.get() # add .get()

此外,当您将system_call函数绑定到按钮时,您调用函数并将结果绑定到command。相反,使用lambda:

b = Button(root, text="Run fuction", command=lambda: system_call('Command call', command(v1, v2,v3)))
相关问题