How should I read and write a configuration file for TkInter?

2024/11/15 7:11:33

I've gathered numbers in a configuration file, and I would like to apply them to buttons. Clicking the button should allow the number to be changed and then re-written to the config file. My current code is as follows:

from tkinter import*
import tkinter as tk
import tkinter.simpledialogdef onChange(i):     btn_list[i].config(text='Updating...',bg='red')  btn_list[i].grid(in_=root,row=rw[i],column=2)ans=tk.simpledialog.askfloat('Updating....', 'What is the current price?')if ans:btn_list[i].config(text='RM {:,.2f}'.format(ans))btn_list[i].config(bg='yellow')c=str(ans)fw=open('dataUpdate.txt','w')fw.write(c)fw.close()root=Tk()Title=['Item','Unit','Price']
Item=['Kopi O','Teh O','Teh Tarik']
Unit= '1 cup'
cl=[0,1,2]
rw=[1,2,3]
btn_list=[]
fr=open('dataUpdate.txt','r')with open('dataUpdate.txt') as input_file:text=input_file.read()strings=text.split()number=[float(item) for item in strings]print(number)fr.close()for k in range(3):btnT1=tk.Button(root,text=Title[k],width=12,bg='light green')btnT1.grid(in_=root,row=0,column=cl[k])for x in range(3):btnT2=tk.Button(root,text=Item[x],width=12)btnT2.grid(in_=root,row=rw[x],column=0)for y in range(3):btnT3=tk.Button(root,text=Unit,width=12)btnT3.grid(in_=root,row=rw[y],column=1)             for z in range(3):btnT4=tk.Button(root,text=('RM {:,.2f}'.format(number[z])),bg='yellow',width=12,\command=lambda i=z:onChange(i))btnT4.grid(in_=root,row=rw[z],column=2)btn_list.append(btnT4)root.mainloop()

Here's a screenshot of my basic configuration file: dataUpdate.txt

Answer

Try this simple example:

from tkinter import*
import tkinter as tk
import tkinter.simpledialog
import configparser
import os.pathdef onChange(i):     btn_list[i].config(text='Updating...',bg='red')  btn_list[i].grid(in_=root,row=rw[i],column=2)ans=tk.simpledialog.askfloat('Updating....', 'What is the current price?')if ans:btn_list[i].config(text='RM {:,.2f}'.format(ans))btn_list[i].config(bg='yellow')c=str(ans)#fw=open('dataUpdate.txt','w')#fw.write(c)#fw.close()#----------------------------------------------# Here you can call update(section, key value) update('Section1', 'number%s' % i, c)#----------------------------------------------root=Tk()Title=['Item','Unit','Price']
Item=['Kopi O','Teh O','Teh Tarik']
Unit= '1 cup'
cl=[0,1,2]
rw=[1,2,3]
btn_list=[]#------------------------------------------------------------------------
config = configparser.RawConfigParser()def init():'Create a configuration file if does not exist'config.add_section('Section1')config.set('Section1', 'number1', '1')config.set('Section1', 'number2', '0.8')config.set('Section1', 'number3', '0.2')with open('dataUpdate.cfg', 'w') as output:config.write(output)#------------------------------------------------------------------------
# check if dataUpdate.cfg exist if not create it   
if not os.path.exists('dataUpdate.cfg'):init()# Read configurations using section and key to get the value
config.read('dataUpdate.cfg')
number = [config.getfloat('Section1', 'number%s' % (i)) for i in range(3)]
#------------------------------------------------------------------------#------------------------------------------------------------
def update(section, key, value):#Update config using section key and the value to change#call this when you want to update a value in configuation file# with some changes you can save many values in many sectionsconfig.set(section, key, value )with open('dataUpdate.cfg', 'w') as output:config.write(output)
#------------------------------------------------------------for k in range(3):btnT1=tk.Button(root,text=Title[k],width=12,bg='light green')btnT1.grid(in_=root,row=0,column=cl[k])for x in range(3):btnT2=tk.Button(root,text=Item[x],width=12)btnT2.grid(in_=root,row=rw[x],column=0)for y in range(3):btnT3=tk.Button(root,text=Unit,width=12)btnT3.grid(in_=root,row=rw[y],column=1)             for z in range(3):btnT4=tk.Button(root,text=('RM {:,.2f}'.format(number[z])),bg='yellow',width=12,\command=lambda i=z:onChange(i))btnT4.grid(in_=root,row=rw[z],column=2)btn_list.append(btnT4)root.mainloop()
https://en.xdnf.cn/q/119443.html

Related Q&A

How to convert this nested dictionary into one single dictionary in Python 3? [duplicate]

This question already has answers here:Convert nested dictionary into a dictionary(2 answers)Flatten nested dictionaries, compressing keys(32 answers)Closed 4 years ago.I have a dictionary like this:a …

How to click unopened tabs where the numbers change

How do I click all the unopened tabs pages where the value changes when you click tabs? (see image below)Take the following script, based off of this question with the following approach:clickMe = wai…

Xlwings / open password protected worksheet in xlsx?

I get an answer how to open a password protected xlsx with xlwings: Xlwings / open password protected xlsx? wb = xlwings.Book("file.xlsx", password="Passw0rd!")But can i also open …

Wrapping an opencv implementaion of an error level analysis algorithm using cython

i have implemented an error level analysis algorithm using c++(opencv version 2.4) and i want to build a python wrapper for it using cython. I have read some part of the documentation of cython for c++…

Setting yticks Location Matplotlib

Im trying to create a plot which has y axis exactly same with this : And Im in this situation and everything is ok until this point:When i try this lines:ax.set_yticks(range(20,67,10)) ax.set_yticklabe…

How to merge list to become string without adding any character in python?

I found that I can join them with -.join(name) but I dont want to add any character. Lets say I have [stanje1, |, st6, , stanje2, |, #] and I want to be like thisstanje1|st6,stanje2|#

Removing a key from a nested dictionary based on value

I previusly asked about adding, and someone helped me out with append. My new problem is trying to delete a key with a nested list, e.g.:JSON:data = {"result":[{"name":"Teddy&q…

Is dot product and normal multiplication results of 2 numpy arrays same?

I am working with kernel PCA in Python and I have to find the values after projecting the original data to the principal components.I use the equation fv = eigvecs[:,:ncomp]print(len(fv))td = fv.T …

Tkinter Entry widget stays empty in larger programs (Python 2)

I want to make a program where, after clicking on a button, a user gets asked for its name, after which the program continues. Im stuck on making the popup return the textstring that has been entered i…

How do i implement this python tree linked list code in dart?

Here is the python codedef tree(root_label, branches=[]):for branch in branches:assert is_tree(branch), branches must be treesreturn [root_label] + list(branches)def label(tree):return tree[0]def branc…