【问题标题】:how to change value of label after button is clicked on Tkinter在Tkinter上单击按钮后如何更改标签的值
【发布时间】:2017-12-22 15:15:14
【问题描述】:

我正在创建一个简单的银行帐户 GUI,当我单击菜单“利息”时,变量从 1 更改为 2,这应该将当前余额的值更改 10%,但是值保持不变,给你洞察力。

from tkinter import *
from random import randint


class BankAccount(object):
    def __init__(self, initial_balance=0):
        self.balance = initial_balance
    def deposit(self, amount):
        self.balance += amount
    def withdraw(self, amount):
        self.balance -= amount       
    def get_balance(self, initial_balance, rate):
        return self.get_balance() * self._rate

class BankAccountWithInterest(BankAccount):
    def __init__(self, initial_balance=0, rate=0.1):
        BankAccount.__init__(self, initial_balance)
        self._rate = rate           
    def interest(self):
        return self.balance * self._rate

balance = (randint(100, 500))
my_account = BankAccount(balance)
my_interest = BankAccountWithInterest(balance)
interest = my_interest.balance + my_interest.interest()

typeOfAccount = "1"
class GUI:
    def __init__(self, master):
        frame = Frame(master)
        frame.pack()


        #Toolbar#

        toolbar = Frame(root)
        toolbar.pack(side=TOP, fill=X)

        #Button#

        button1 = Button(toolbar, text="Deposit", width = 13,    command=self.depositBalance)
        button2 = Button(toolbar, text="Withdraw",width = 13, command=self.depositWithdraw)
        button1.pack(side=LEFT)
        button2.pack(side=RIGHT)

        #Menu#

        subMenu = Menu(menu)
        menu.add_cascade(label="Type of Account", menu=subMenu)
        subMenu.add_command(label="Standard", command= self.standard)
        subMenu.add_command(label="Interest", command= self.interest)

        #Textbox#

        self.text = Entry(root)
        self.text.pack()

        #Labels#

        w = Label(root, text="Current Balance:")
        w.pack()
        w1 = tkinter.StringVar()
        if typeOfAccount == "1":
            w1 = Label(root, text=my_account.balance)
            w1.pack()
        elif typeOfAccount == "2":
            w1.set(text=interest)
            w1.pack()


    def depositBalance(self):
            a = int(self.text.get())
            my_account.balance = a + my_account.balance
            print(my_account.balance)

    def depositWithdraw(self):
            a = int(self.text.get())
            my_account.balance = my_account.balance - a
            print(my_account.balance)         

    def standard(self):
        typeOfAccount = "1"

    def interest(self):
        typeOfAccount = "2"


root = Tk()
menu = Menu(root)
root.config(menu=menu)
root.title("Bank Account")
root.minsize(width=250, height=100)
root.maxsize(width=300, height=150)
GUI(root)

root.mainloop()

【问题讨论】:

  • 这段代码的问题比我原先想象的要多。请提供Minimal, Complete, and Verifiable example
  • 你能给出你的见解吗?将不胜感激
  • 我已经用您的代码的修订版本更新了我的答案。让我知道这是否是您想要完成的目标。

标签: python python-3.x oop inheritance tkinter


【解决方案1】:

您的代码存在几个问题。多个类文件似乎没有像您认为的那样工作,而且有些事情是错误的。我已将您的程序重新设计成我认为您正在尝试做的事情,并且我已将所有内容都移到了 1 个大类中,因为在这种情况下它更有意义。通过在类之外创建变量并创建多个类,您使事情变得比需要的更复杂。使用多个类并没有什么问题,但你这样做的方式让事情变得比它需要的更困难。

我做的第一件事是创建我们将要使用的所有类变量/属性。

为了让我们以后的工作更轻松,我通过将self. 作为所有变量/小部件名称的前缀,使每个小部件和变量都成为类属性。这将使我们能够毫无问题地与任何类方法中的每个属性进行交互和更改,并且如果您在以后添加更多选项,这些属性将已经定义并准备好更改。

接下来,我将所有单独的类方法移到主类中,以便于使用。

我将您关于帐户类型的 if/else 语句替换为方法。这将允许我们在账户类型更改或从余额中添加或删除金额时更新标签以显示余额或利息。

我修改了depositBalancedepositWithdraw 方法以进行一些错误处理,因为您的输入字段不仅限于数字,如果用户输入其他内容或将其留空,可能会导致错误。

我更改了standardinterest 方法来更新typeOfAccount 属性并通过调用type_account 方法来更新标签。

最后但并非最不重要的一些一般性清理,因此代码没有毫无意义的间距,并确保我们遵循 DRY(不要重复自己)标准。

下面是经过我上面提到的所有更改的重新编写的代码。让我知道这是否有帮助,如果您对任何事情感到困惑。

from tkinter import *
from random import randint

class GUI:
    def __init__(self, master):

        self.master = master
        self.typeOfAccount = "1"
        self.balance = (randint(100, 500))
        self.rate = 0.1

        self.frame = Frame(master)
        self.frame.pack()

        self.toolbar = Frame(root)
        self.toolbar.pack(side=TOP, fill=X)

        self.button1 = Button(self.toolbar, text="Deposit", width = 13, command=self.depositBalance)
        self.button2 = Button(self.toolbar, text="Withdraw",width = 13, command=self.depositWithdraw)
        self.button1.pack(side=LEFT)
        self.button2.pack(side=RIGHT)

        self.menu = Menu(self.master)
        self.master.config(menu = self.menu)
        self.subMenu = Menu(self.menu)
        self.menu.add_cascade(label="Type of Account", menu=self.subMenu)
        self.subMenu.add_command(label="Standard", command=self.standard)
        self.subMenu.add_command(label="Interest", command=self.interest)

        self.text = Entry(self.master)
        self.text.pack()

        self.w = Label(root, text="Current Balance: {}".format(self.balance))
        self.w.pack()
        #removed "tkinter." not needed because of the type of import you used
        self.w1 = StringVar()

    def type_account(self):
        if self.typeOfAccount == "1":
            self.w.config(text="Current Balance: {}".format(self.balance))

        elif self.typeOfAccount == "2":
            interest = self.balance * self.rate
            self.w.config(text="Current Balance: {}".format(interest))

    def depositBalance(self):
        try:
            if int(self.text.get()) > 0:
                a = int(self.text.get())
                self.balance = a + self.balance
                self.type_account()
        except:
            print("Blank or non numbers in entry field")

    def depositWithdraw(self):
        try:
            if int(self.text.get()) > 0:
                a = int(self.text.get())
                self.balance = self.balance - a
                self.type_account()
        except:
            print("Blank or non numbers in entry field")

    def standard(self):
        self.typeOfAccount = "1"
        self.type_account()

    def interest(self):
        self.typeOfAccount = "2"
        self.type_account()

if __name__ == "__main__":

    root = Tk()
    root.title("Bank Account")
    root.minsize(width=250, height=100)
    root.maxsize(width=300, height=150)

    app = GUI(root)

    root.mainloop()

【讨论】:

  • 已经尝试过了,并且在单击“兴趣”菜单选项时不会更改标签值
  • @MohamedIsmail:我已经更新了我的答案,以反映我认为修复您的程序所需的所有更改。如果有帮助,请告诉我。
【解决方案2】:

例如,您应该设置self.w1,(而不仅仅是w1),然后您可以从该类中的任何实例方法更新文本。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-31
    相关资源
    最近更新 更多