【问题标题】:Setting variables using Tkinter使用 Tkinter 设置变量
【发布时间】:2015-05-26 14:58:00
【问题描述】:

在使用 Tkinter 时大吃一惊——我想做的是一个运行系统调用函数的小型 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()

收到一个错误,指出无法对字符串对象和实例对象进行分类。

【问题讨论】:

  • 您的问题到底是什么?为什么要调用get,而不是将StringVar 对象本身分配给textvariable
  • command= system_call(command(v1, v2,v3)) 这将调用 system_call将函数作为回调绑定到按钮。
  • 我要调用系统调用! - 我收到一个错误,说字符串和实例对象不能被分类。

标签: python python-2.7 tkinter


【解决方案1】:

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

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

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)))

【讨论】:

  • 谢谢!先看看这个,所以有点困惑!
  • 我建议不要在这种情况下使用 lambda。 Lambda 对很多人来说很难理解,并且只有在没有更好的选择时才应该使用。最好为按钮创建一个专门的命令,这将使程序随着时间的推移更容易维护。
猜你喜欢
  • 1970-01-01
  • 2023-04-02
  • 1970-01-01
  • 1970-01-01
  • 2011-12-29
  • 2012-03-01
  • 2021-12-29
  • 2020-07-20
  • 2021-05-24
相关资源
最近更新 更多