如何在tkinter中覆盖文本文件中的数据

时间:2017-09-14 09:26:11

标签: python tkinter tkinter-entry toplevel

我正在创建一个带有tkinter的程序,它带有一个存储在文本文件中的默认名称和密码。登录后,您需要打开 public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); // Setup the new range seek bar RangeSeekBar<Integer> rangeSeekBar = new RangeSeekBar<>(this); // Set the range rangeSeekBar.setRangeValues(15, 90); rangeSeekBar.setSelectedMinValue(20); rangeSeekBar.setSelectedMaxValue(88); // Add to layout FrameLayout layout = (FrameLayout) findViewById(R.id.seekbar_placeholder); layout.addView(rangeSeekBar); // Seek bar for which we will set text color in code RangeSeekBar rangeSeekBarTextColorWithCode = (RangeSeekBar) findViewById(R.id.rangeSeekBarTextColorWithCode); rangeSeekBarTextColorWithCode.setTextAboveThumbsColorResource(android.R.color.holo_blue_bright); rangeSeekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() { @Override public void onRangeSeekBarValuesChanged(RangeSeekBar<Integer> bar, Integer minValue, Integer maxValue) { int hours = minValue / 4; // it will return hours. int minutes = (minValue % 4) * 15; Toast.makeText(getApplicationContext(), hours + " Hours - " + hours + ":" + minutes, Toast.LENGTH_SHORT).show(); } }); } 窗口并输入要在后续登录中使用的名称和密码。我已经定义了我的变量,但如果我想覆盖文本文件,我会收到以下内容:

  

错误“NameError:名称'e1'未定义”

我知道我已定义。

Toplevel

1 个答案:

答案 0 :(得分:0)

所以你有几个选择,但一般来说你有两个主要问题。

第一个问题是在创建.pack()e1条目字段后使用e2。这是get()方法的问题,因为如果以这种方式打包,几何管理器将返回None。正确的方法是首先使用e1 = Entry(ch, width=20)创建窗口小部件,然后使用e1.pack()将其打包到下一行,这样get()就可以使用e1

第二个问题是局部变量与全局变量的关系。您已在函数e1内创建了e2change_login(),并且没有告诉python e1e2是全局变量,它会自动假设您希望它们为局部变量。这意味着只能从创建它们的函数中访问变量。

你有几个选择我会为你解决。

1)快速和脏选项是将e1e2指定为全局变量。这可以通过global var_name, var2_name, and_so_on来完成,因此在这种情况下,请将此行添加到change_login():save_changes()函数的顶部:

global e1, e2

这告诉python将e1e2添加到全局名称空间,它将允许save_changes()使用全局名称空间中的变量。

2)另一种方法是使用button命令将2个变量传递给save_changes()。我们需要使用lambda来实现这一点,我们可以通过添加:

来实现这一目标
command = lambda e1=e1, e2=e2: save_changes(e1, e2)

change_login()中创建的按钮,并将{2}参数添加到save_changes(),如下所示:

save_changes(e1, e2)

这与第一个选项一样有效,也避免使用全局变量。

3)第三种选择是将整个程序创建为类,并使用类属性允许变量与类中的所有方法一起使用。

以下是使用第一个选项的代码示例:

import sys
from tkinter import messagebox
from tkinter import *

now = open("pass.txt","w+")
now.write("user\n")
now.write("python3")
now.close()

def login_in():
    with open("pass.txt") as f:
        new = f.readlines()
        name = new[0].rstrip()
        password = new[1].rstrip()
    if entry1.get() == name and entry2.get() == password:
        root.deiconify()
        log.destroy()
    else:
        messagebox.showerror("error","login Failed")

def change_login():
    global e1, e2
    ch = Toplevel(root)
    ch.geometry('300x300')
    e1 = Entry(ch, width=20)
    e1.pack()
    e2 = Entry(ch, width=20)
    e2.pack()
    sb = Button(ch, text="save", command=save_changes).pack()

def save_changes():  # function to change data in the txt file
    global e1, e2
    data = e1.get() + "\n" + e2.get() # removed space after \n
    with open("pass.txt", "w") as f:
        f.writelines(data)

root= Tk()
log = Toplevel()
root.geometry("350x350")
log.geometry("200x200")

entry1 = Entry(log)
entry2 = Entry(log)
button1 = Button(log, text="Login", command=login_in) #Login button

entry1.pack()
entry2.pack()
button1.pack()

label = Label(root, text="welcome").pack()
butt = Button(root, text="change data in file", command=change_login).pack()

root.withdraw()
root.mainloop()

以下是使用第二个选项的代码示例:

import sys
from tkinter import messagebox
from tkinter import *

now = open("pass.txt","w+")
now.write("user\n")
now.write("python3")
now.close()

def login_in():
    with open("pass.txt") as f:
        new = f.readlines()
        name = new[0].rstrip()
        password = new[1].rstrip()
    if entry1.get() == name and entry2.get() == password:
        root.deiconify()
        log.destroy()
    else:
        messagebox.showerror("error","login Failed")

def change_login():
    ch = Toplevel(root)
    ch.geometry('300x300')
    e1 = Entry(ch, width=20)
    e1.pack()
    e2 = Entry(ch, width=20)
    e2.pack()
    Button(ch, text="save", command=lambda e1=e1, e2=e2: save_changes(e1, e2)).pack()

def save_changes(e1, e2):  # function to change data in the txt file
    data = e1.get() + "\n" + e2.get() # removed space after \n
    with open("pass.txt", "w") as f:
        f.writelines(data)

root= Tk()
log = Toplevel()
root.geometry("350x350")
log.geometry("200x200")

entry1 = Entry(log)
entry2 = Entry(log)
button1 = Button(log, text="Login", command=login_in) #Login button

entry1.pack()
entry2.pack()
button1.pack()

label = Label(root, text="welcome").pack()
butt = Button(root, text="change data in file", command=change_login).pack()

root.withdraw()
root.mainloop()

以下是转换为类并使用类属性避免使用全局变量的代码示例。

import sys
from tkinter import messagebox
from tkinter import *


class MyApp(Frame):

    def __init__(self, master, *args, **kwargs):
        Frame.__init__(self, master, *args, **kwargs)

        self.master = master
        self.master.withdraw()

        self.log = Toplevel()
        self.master.geometry("350x350")
        self.log.geometry("200x200")

        self.entry1 = Entry(self.log)
        self.entry2 = Entry(self.log)
        self.button1 = Button(self.log, text="Login", command=self.login_in)

        self.entry1.pack()
        self.entry2.pack()
        self.button1.pack()

        Label(root, text="welcome").pack()
        Button(root, text="change data in file", command=self.change_login).pack()

    def login_in(self):
        with open("pass.txt") as f:
            new = f.readlines()
            name = new[0].rstrip()
            password = new[1].rstrip()
        if self.entry1.get() == name and self.entry2.get() == password:
            self.master.deiconify()
            self.log.destroy()
        else:
            messagebox.showerror("error","login Failed")

    def change_login(self):
        ch = Toplevel(self.master)
        ch.geometry('300x300')
        self.e1 = Entry(ch, width=20)
        self.e1.pack()
        self.e2 = Entry(ch, width=20)
        self.e2.pack()
        Button(ch, text="save", command=self.save_changes).pack()

    def save_changes(self):
        data = "{}\n{}".format(self.e1.get(), self.e2.get())
        with open("pass.txt", "w") as f:
            f.writelines(data)


if __name__ == "__main__":
    now = open("pass.txt","w+")
    now.write("user\n")
    now.write("python3")
    now.close()

    root = Tk()
    app = MyApp(root)
    root.mainloop()