首页 > 解决方案 > 如何分配字典值,以便在将密钥作为帐户输入时,它在 Kivy 中将值作为密码返回?

问题描述

.py 文件

import kivy
from kivy.app import App
from kivy.uix.widget import Widget
from kivy.uix.gridlayout import GridLayout
from kivy.uix.textinput import TextInput
from kivy.properties import ObjectProperty
from kivy.uix.label import Label
from kivy.graphics import Color, Rectangle  
from kivy.uix.button import Button

class MyGrid(Widget):
    account = ObjectProperty(None)
    password = ObjectProperty(None)

def button(self):
    print('Account Name:', self.account.text, 'Password:', self.password.text)
    self.account.text = ' '
    self.password.text = ' '

passwords = {'email1': '', 'email2': '', 'Nintendo': '', 'email3': ''}

email1 = ''
email2 = ''
email3 = ''

class pwStorer(App):
    def build(self):
        return MyGrid()

if __name__ == '__main__':
    pwStorer().run() 

.kv 文件

<MyGrid>

account: account
password: password

GridLayout:
    cols: 1
    size: root.width, root.height

    GridLayout:
        cols: 2

        Label:
            text: 'Account Name:'

        TextInput:
            id: account
            multiline: False

        Label:
            text: 'Password:'

        TextInput:
            id: password
            multiline: False

    Button:
        text: 'Enter'
        on_release:

本质上,当按钮被释放时,它应该从与键(或“帐户名”)关联的字典“密码”中返回一个值。我该怎么做?(最好在 .kv 文件中)。我对 Python 还很陌生,到处搜索,但似乎无法弄清楚这一点。谢谢!

标签: dictionarykivy

解决方案


对于您的Button,您可以使用:

    Button:
        text: 'Enter'
        on_release: password.text=app.get_password(account.text)

然后,在pwStorer

class pwStorer(App):
    def build(self):
        return MyGrid()

    def get_password(self, user_name):
        try:
            pswd = passwords[user_name]
            return pswd
        except:
            return '***** No Such User****'

推荐阅读