使用按钮更改变量的值(Tkinter) [英] Change the value of a variable with a button (Tkinter)

查看:199
本文介绍了使用按钮更改变量的值(Tkinter)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想用一个按钮来更改变量的值,我不想那样创建一个新的完整函数:

I want to change the value of a variable just with a button, i don't want to create a new entire function just like that:

from Tkinter import *
variable = 1
def makeSomething():
    global variable
    variable = 2
root = Tk()
myButton = Button(root, text='Press me',command=makeSomething).pack()

我该怎么做?
(我需要对六个按钮执行此操作,使其无法实现六个功能)

How i can do that? (I need to do that for six buttons, making six functions it's not an option)

推荐答案


我需要使它包含6个按钮...

i need to make this for 6 buttons...

如果每个按钮修改了相同的全局变量,则必须 makeSomething 接受参数:

If each button modifies the same global variable, then have makeSomething accept a value parameter:

from Tkinter import *
variable = 1
def makeSomething(value):
    global variable
    variable = value
root = Tk()
Button(root, text='Set value to four',command=lambda *args: makeSomething(4)).pack()
Button(root, text='Set value to eight',command=lambda *args: makeSomething(8)).pack()
Button(root, text='Set value to fifteen',command=lambda *args: makeSomething(15)).pack()
#...etc

如果每个按钮修改了一个不同的全局变量,则将所有全局变量压缩为一个全局变量,然后可以修改 makeSomething

If each button modifies a different global, then condense all your globals into a single global dict, which makeSomething can then modify.

from Tkinter import *
settings = {"foo": 1, "bar": 1, "baz": 1}

def makeSomething(name):
    settings[name] = 2

root = Tk()
Button(root, text='Set foo',command=lambda *args: makeSomething("foo")).pack()
Button(root, text='Set bar',command=lambda *args: makeSomething("bar")).pack()
Button(root, text='Set baz',command=lambda *args: makeSomething("baz")).pack()
#...etc

在两种情况下,您仍然只需要一个功能。

In either case, you still only require one function.

方式,请不要这样做:

myButton = Button(root).pack()

这会将 pack()的结果分配给myButton,因此myButton将为,而不是引用您的按钮。而是:

This assigns the result of pack() to myButton, so myButton will be None instead of referring to your button. Instead, do:

myButton = Button(root)
myButton.pack()

这篇关于使用按钮更改变量的值(Tkinter)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆