Python 使用按钮更改变量的值 (Tkinter)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24911805/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change the value of a variable with a button (Tkinter)
提问by Marc43
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)
我怎么能这样做?(我需要为六个按钮这样做,使六个功能不是一个选项)
采纳答案by Kevin
i need to make this for 6 buttons...
我需要为 6 个按钮做这个...
If each button modifies the same global variable, then have makeSomething
accept a value
parameter:
如果每个按钮修改相同的全局变量,则必须makeSomething
接受一个value
参数:
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
If each button modifies a different global, then condense all your globals into a single global dict, which makeSomething
can then modify.
如果每个按钮修改不同的全局变量,那么将所有全局变量压缩为一个全局字典,然后makeSomething
可以修改。
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.
在任何一种情况下,您仍然只需要一个函数。
By the way, don't do this:
顺便说一句,不要这样做:
myButton = Button(root).pack()
This assigns the result of pack()
to myButton, so myButton will be None
instead of referring to your button. Instead, do:
这会将 的结果分配pack()
给 myButton,因此 myButton 将None
代替您的按钮。相反,请执行以下操作:
myButton = Button(root)
myButton.pack()
回答by Deltix
Update : I have it working (almost) fine This code works but I'd like to display in real time And when I uncoment the 2 things it doesn't do anything anymore
更新:我让它工作(几乎)很好这段代码有效,但我想实时显示当我取消注释这 2 件事时,它不再做任何事情
def BotPlay_Button():
nPlay = entryN.get()
jlist = [Joueur(File1,True,File1),Joueur(File2,True,File1)]
Partie = Partie_Object(jlist)
for i in range(int(nPlay)):
Play_Partie(Partie)
xList.append(i)
y1List.append(bot1.score)
y2List.append(bot2.score)
# windo.update_idletasks()
# windo.update()