在 tkinter 中保留一个变量 [英] Keep a variable in tkinter

查看:24
本文介绍了在 tkinter 中保留一个变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有这样的代码:

def awnser():
    a = 1
    print(a)
    return (a)

def opzP():
    opz = "+"
    print(opz)
    print(a)
    return

我想单击第一个按钮并运行命令awnser".但后来我想点击另一个按钮,命令opzP"应该运行.但它不存储变量a.我该如何存储.谢谢你的帮助^^

I want to click at the first button and the command "awnser" run. But later I want to click on another button and the command "opzP" should run. But it doesnt store the variable a. How can I store that. Thank you for your help ^^

Return 命令等等...

The Return command and so on...

def awnser():
    a = 1
    print(a)
    return (a)

def opzP():
    opz = "+"
    print(opz)
    print(a)
    return

错误消息而不是变量.

推荐答案

不使用OOP,最简单的方法就是创建一个全局变量:

Witout using OOP, the easiest way to do so is to create a global variable:

a = 0
def do1():
    global a
    a=1
def do2():
    global a
    print(a)

但那是糟糕的方式.因为它使用了一个全局变量.更好的方法是:

But that's the bad way. Because it uses a global variable. The better way is:

class Funs:
    def __init__(self):
        self.a = 0
    def answer(self):
        self.a = 1
        print(self.a)
        return (self.a)
    def opzP(self):
        self.opz = "+"
        print(self.opz)
        print(self.a)
        return
obj = Funs()
Button(command=obj.answer).pack()
Button(command=obj.opzP).pack()

希望对你有帮助!

这篇关于在 tkinter 中保留一个变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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