简体   繁体   中英

How can I save inputs from Python Tkinter into a txt file?

from tkinter import *
from tkinter import messagebox
from tkinter import END
from typing import  *
from tkinter import Tk
import tweepy
import time



window = Tk()
window.title("Tweetio")
window.minsize(1000,800)
top_frame = Frame(window).pack()
bottom_frame = Frame(window).pack()
btns_frame = Frame(window, pady = 10)
btns_frame.pack()


def openKey():
    
    newwin = Toplevel(window)
    newwin.title('Insert API Key')
    newwin.geometry('500x250')
    newwin.resizable(0, 0)
    newwin.columnconfigure(0, pad=3)
    newwin.columnconfigure(1, pad=3)
    newwin.rowconfigure(0, pad=6)
    newwin.rowconfigure(1, pad=6)
    newwin.rowconfigure(2, pad=6)
    newwin.rowconfigure(3, pad=6)
    newwin.rowconfigure(4, pad=6)
    Label(newwin, text = "API KEY:").grid(row = 0)
    Label(newwin, text = "API KEY SECRET:").grid(row = 1)
    Label(newwin, text = "BEARER TOKEN:").grid(row = 2)
    Label(newwin, text = "ACCESS TOKEN:").grid(row = 3)
    Label(newwin, text = "ACCESS TOKEN SECRET:").grid(row = 4)
    api_key = Entry(newwin).grid(row = 0, column = 1)
    api_secret_key = Entry(newwin).grid(row = 1, column = 1)
    bearer_token = Entry(newwin).grid(row = 2, column = 1)
    access_token = Entry(newwin).grid(row = 3, column = 1)
    access_token_secret = Entry(newwin).grid(row = 4, column = 1)
     
     
    def saveEntry(): 
        with open ('api_keys.text', 'w', encoding='utf-8') as f:
            f.write(input(api_key) + '\n')
            f.write(input(api_secret_key) + '\n')
            f.write(input(bearer_token) + '\n')
            f.write(input(access_token) + '\n')
            f.write(input(access_token_secret) + '\n')

    Button(newwin, text = "Enter", width = 30, height = 5, pady = 10, fg = "Black", bg = "Gold", command = lambda:saveEntry).grid(row = 8, column = 1)

I'm trying to save the user input into a txt file to be used later in the program. I want to save all 5 inputs into the same txt folder. Then, call back on the text file with 'r'. It's tkinter for Python. Any ideas? Any input would be much appreciated.

I tried to use 'w' and f.write but it wasn't working.

First, the Entry widgets are not being assigned to variables properly, so you will not be able to retrieve their values. Use code below instead:

api_key = Entry(newwin)
api_key.grid(row = 0, column = 1)

In addition, you should use the get method on the Entry widgets instead of input to retrieve the user input through the Entry widgets, like this:

api_key_value = api_key.get()

along with this:

with open ('api_keys.text', 'w', encoding='utf-8') as f:
    f.write(api_key_value + '\n')
    ...

Hope this could help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM