Kivy更新小工具

时间:2016-09-17 03:01:33

标签: python kivy

我读了一个名为data.txt的文本文件,其中包含用户名和密码。文本文件的格式为:

USERNAME1
密码1
USERNAME2
密码2
USERNAME3
USERNAME3

我读了用户名并为每个用户名创建一个相应的按钮。当我第一次启动程序时,它会显示data.txt中的所有内容并且可以正常运行。但是,当我使用该程序添加用户时,它不会更新主屏幕上的用户列表。我该如何更新清单?

import kivy
from kivy.app import App
from kivy.uix.screenmanager import Screen, ScreenManager, NoTransition
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.core.window import Window
from kivy.config import Config
from kivy.properties import ObjectProperty
from kivy.uix.textinput import TextInput
from kivy.uix.popup import Popup
from numpy import loadtxt
from kivy.uix.widget import Widget
from os.path import sep, expanduser, isdir, dirname
from kivy.uix.stacklayout import StackLayout
from functools import partial
from kivy.uix.scrollview import ScrollView
from kivy.uix.gridlayout import GridLayout

class AddUserWindow(Screen):
    def __init__(self,**kwargs):
        super (AddUserWindow,self).__init__(**kwargs)
        addNewUserLayout = FloatLayout()
        newUserLabel = Label(text="User Name:", font_size='15dp', size_hint = (.5, .05), pos = (500, 450), halign = 'right')
        passwordLabel = Label(text="Password:", font_size='15dp', size_hint = (.5, .05), pos = (500, 400), halign = 'right')
        confirmPasswordLabel = Label(text="Confirm Password:", font_size='15dp', size_hint = (.5, .05), pos = (500, 350), halign = 'right')
        self.newUserInput = TextInput(text = "", size_hint = (.25, .05), pos = (875, 450), font_size='15dp', multiline = False, write_tab = False)
        self.passwordInput = TextInput(text = "", password = True, size_hint = (.25, .05), pos = (875, 400), font_size='15dp', multiline = False, write_tab = False)
        self.confirmPasswordInput = TextInput(text = "", password = True, size_hint = (.25, .05), pos = (875, 350), font_size='15dp', multiline = False, write_tab = False)
        cancelButton = Button(text="Cancel",size_hint = (.2, .05), pos =  (650,0))
        cancelButton.bind(on_press = self.changeToMainWindow)
        okButton = Button(text="Ok",size_hint = (.2, .05), pos =  (350,0))
        okButton.bind(on_press=self.newUserCheck)
        addNewUserLayout.add_widget(cancelButton)
        addNewUserLayout.add_widget(okButton)
        addNewUserLayout.add_widget(newUserLabel)
        addNewUserLayout.add_widget(passwordLabel)
        addNewUserLayout.add_widget(confirmPasswordLabel)
        addNewUserLayout.add_widget(self.newUserInput)
        addNewUserLayout.add_widget(self.passwordInput)
        addNewUserLayout.add_widget(self.confirmPasswordInput)

        self.add_widget(addNewUserLayout)

    def newUserCheck(self, *args):

        if self.newUserInput.text == "":
            content = Button(text = 'Close')
            popup = Popup(title = 'Please enter user name', size_hint = (.4, .15), content = content, auto_dismiss = False)
            content.bind(on_press = popup.dismiss)
            popup.open()
            return

        if self.passwordInput.text == "":
            content = Button(text = 'Close')
            popup = Popup(title = 'Please enter password', size_hint = (.4, .15), content = content, auto_dismiss = False)
            content.bind(on_press = popup.dismiss)
            popup.open()
            return

        if self.confirmPasswordInput.text == "":
            content = Button(text = 'Close')
            popup = Popup(title = 'Please confirm password', size_hint = (.4, .15), content = content, auto_dismiss = False)
            content.bind(on_press = popup.dismiss)
            popup.open()
            return

        if self.passwordInput.text != self.confirmPasswordInput.text:
            content = Button(text = 'Close')
            popup = Popup(title = 'Passwords must match', size_hint = (.4, .15), content = content, auto_dismiss = False)
            content.bind(on_press = popup.dismiss)
            popup.open()
            return


        file = open('data.txt', 'r')
        initial = file.readlines()
        databaselines = sum(1 for line in open('data.txt'))
        file.close()


        users = databaselines / 2
        data = [[0 for x in range(2)] for y in range(users)]
        currLine = 0
        range(users)
        for i in range(users):
            data[i][0] = initial[currLine].rstrip()
            data[i][1] = initial[currLine + 1].rstrip()
            currLine += 2

        inDatabase = 0
        for i in range(users):
            if data[i][0] == self.newUserInput.text:
                inDatabase = 1
                break
        if inDatabase == 1:
            content = Button(text = 'Close')
            popup = Popup(title = 'Already in database', size_hint = (.4, .15), content = content, auto_dismiss = False)
            content.bind(on_press = popup.dismiss)
            popup.open()
            return

        with open("data.txt", "a") as dataFile:
            dataFile.write(self.newUserInput.text + "\n")
            dataFile.write(self.passwordInput.text + "\n")
        self.changeToMainWindow


    def changeToMainWindow(self, *args):
        self.newUserInput.text = ""
        self.passwordInput.text = ""
        self.confirmPasswordInput.text = ""
        self.manager.current = 'mainScreen'

class MainWindow(Screen):

    def __init__(self,**kwargs):
        super (MainWindow,self).__init__(**kwargs)

        self.mainLayout = FloatLayout()

        logoutButton = Button(text="Logout",size_hint = (.2, .1), pos =  (650,0))
        logoutButton.bind(on_press = exit)
        addNewUserButton = Button(text="New User",size_hint = (.2, .1), pos =  (350,0))
        addNewUserButton.bind(on_press=self.changeToAddUser)
        self.mainLayout.add_widget(logoutButton)
        self.mainLayout.add_widget(addNewUserButton)
        file = open('data.txt', 'r')
        initial = file.readlines()
        databaselines = sum(1 for line in open('data.txt'))
        file.close()


        users = databaselines / 2
        data = [[0 for x in range(2)] for y in range(users)]
        currLine = 0
        range(users)
        for i in range(users):
            data[i][0] = initial[currLine].rstrip()
            data[i][1] = initial[currLine + 1].rstrip()
            currLine += 2

        self.layout = GridLayout(cols=1, spacing=10, size_hint_y=None)
        self.layout.bind(minimum_height=self.layout.setter('height'))
        for i in range(users):
            self.btn = Button(text=data[i][0], size_hint_y=None, height=40)
            self.layout.add_widget(self.btn)
        self.root = ScrollView(size_hint=(.45, None), pos = (600, 100), size=(Window.width, Window.height))
        self.root.add_widget(self.layout)

        self.mainLayout.add_widget(self.root)
        self.add_widget(self.mainLayout)




    def changeToAddUser(self, *args):
        self.manager.current = 'addUserScreen'



class TestApp(App):
        def build(self):
            self.my_screenmanager = ScreenManager(transition = NoTransition())
            self.mainScreen = MainWindow(name='mainScreen')
            self.addUserScreen = AddUserWindow(name = 'addUserScreen')
            self.my_screenmanager.add_widget(self.mainScreen)
            self.my_screenmanager.add_widget(self.addUserScreen)

            Window.size = (1200, 800)
            return self.my_screenmanager

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

提前非常感谢!!

1 个答案:

答案 0 :(得分:0)

您可以定义一个功能,将相应的小部件添加到布局中,或者您可以清理"布局并再次从数据库中读取每个用户。如果你有很多用户,这可能需要一段时间。

通过功能添加用户:

class MainWindow(Screen):

    def __init__(self,**kwargs):
        super (MainWindow,self).__init__(**kwargs)

        [... create initial widgets ...]

        [... read users from database ...]

        for i in range(users):
            self.add_user(data[i][0]

        self.root = ScrollView(size_hint=(.45, None), pos = (600, 100), size=(Window.width, Window.height))
        self.root.add_widget(self.layout)

        self.mainLayout.add_widget(self.root)
        self.add_widget(self.mainLayout)

    def add_user(self, text):
         button = Button(text=text, size_hint_y=None, height=40)
         self.layout.add_widget(button)

然后添加新用户时:

def newUserCheck(self, *args):

    [... do checks ...]
    [... write to file ...]

    # replace `text` with whatever text you want to display
    self.manager.get_screen("mainScreen").add_user(text) 

    # in your shown code you missed the () on this function call
    self.changeToMainWindow()

另外,我个人发现您的代码相对难以阅读。你可以创建一些函数并调用它们,例如create_initial_widgetsread_users_from_databasewrite_user_to_database