So I need a drop down menu, where the user picks his/her client, and it returns information about that client.
lets say i have a file:
["client1", "client2", "client3"]
and I have this code:
from tkinter import *
master = Tk()
with open('ubclientlistvars.txt', 'r') as clients:
clients = (clients.readlines())
variable = StringVar(master)
variable.set("Choose Client")
w = OptionMenu(master, variable, clients)
w.pack()
mainloop()
how would I draw the clients from the file into the drop down menu?
When I run this code, i get these two options:
Choose Client and {["client1", "client2", "client3"]}
You need to actually parse that file. If the file contents are what you posted, then readlines() is just returning a single line of text. It does not magically convert the file contents into a Python object. Suppose the file was:
client1
client2
client3
Then you could use something like clients = [i.strip() for i in f.readlines()] to get a proper list of clients and can pass them to OptionMenu:
w = OptionMenu(master, variable, *clients)
If you cannot change the file format then you will need to clean up the input before displaying it...
import re
data = f.read() # ["client1", "client2", "client3"]
data = re.sub('["\[\]]', '', data) # remove the ", [, and ] characters
clients = data.split(',') # split the list of clients on the comma
Related
I am making python based Email broadcasting in which i have created entries like email, pass, there is csv browse as well which will brose a Email_list_container file and a submit button which will call a send mail function to send bulk email along with attachment, problem is when browse is used to grab emails from csv it stores to a variable and then return to function but when I call this variable in send mail function is does not allow me to use it there. same with attachment function is is not coming in send mail function either.
i have tried Global
newvar = browse()
and calling new var but this calls whole function to pop-up again new window to open another file which does not make any sense.
help me guys.
from tkinter import *
import tkinter.messagebox as msg
import smtplib as smtp
import csv
from itertools import chain
#browse function which stores value from csv file
def browse():
from itertools import chain
file_path=filedialog.askopenfilename(title="Open CSV file")
with open(file_path) as csvfile:
read = csv.reader(csvfile)
for row in read:
ini_list.append(row)
flatten_list = list(chain.from_iterable(ini_list))
rcvr_emails =list(flatten_list)
# print(rcvr_emails)
file_label = Label(window,text=file_path, border=0, bg='#BAE1E3',font="inter 10", fg="grey").place(x=330,y=230)
recemail = rcvr_emails
#what i want is submit function to grab a variable from browse function as email list
def submit():
try:
email = login_email.get()
pass_word = login_pass.get()
subject = email_subject.get()
body = email_body.get()
server = smtp.SMTP("smtp.gmail.com",587)
server.starttls()
server.ehlo()
server.login(email,pass_word)
massage = "subject:{}\n\n{}".format(subject,body)
server.sendmail(email,recemail,massage)
server.quit()
msg.showinfo("Status","Mails have been sent to the Targatted Email's List.\nThank You for using our services.")
except:
msg.showwarning("ERROR","SMTP API could not login the credentials,\nPlease check Email & Password then try again.")
Just return recemail from browse function then pass it as argument to submit function:
def browse():
from itertools import chain
file_path=filedialog.askopenfilename(title="Open CSV file")
with open(file_path) as csvfile:
read = csv.reader(csvfile)
for row in read:
ini_list.append(row)
flatten_list = list(chain.from_iterable(ini_list))
rcvr_emails =list(flatten_list)
# print(rcvr_emails)
file_label = Label(window,text=file_path, border=0, bg='#BAE1E3',font="inter 10", fg="grey").place(x=330,y=230)
recemail = rcvr_emails
return recemail
def submit(email_list):
// your code
Then in your main program:
received_email = browse()
submit(received_email)
Or in one line:
submit(browse())
I am building a program that edits a .toml config file, take this for example:
This is one of the sections from the entire .toml config file:
[APU]
apu = "any" # Audio system. Use: [any, nop, sdl,xaudio2]
Normally the users changes the options manually for example if they want to change the apu they just replace the any inside quotation marks ("") with xaudio2 for example.
I want to create a code which presents the setting (apu = " "), and the options that the user has (any,xaudio,nop...)
and let the user choose between the options.
This was the code I originally wrote:
f = open("config.toml", "r")
fread = f.read()
### APU Options ###
nop = fread.replace('apu = "any"', 'apu = "nop"')
sdl = fread.replace('apu = "any"', 'apu = "sdl"')
xaudio2 = fread.replace('apu = "any"', 'apu = "xaudio2"')
### Write the New File ####
with open("config.toml", "w") as f:
f.write(xaudio2)
this code lacks something, when a user changes the apu to xaudio2 with this exact code, after the user re opens the program(this python code) for changing the apu again , the python code can not detect the original code since it was:
apu = "any"
and now after the user has changed it to xaudio2 It will be this:
apu = "xaudio2"
the python code looks only for the apu = "any" to change and replace any with other options.
What do you think is the solution? (when one of the settings in the config changes)
How to replace string after specific character using python
I have a file with below contents
The Test file contents are as below "Test1"{
Serial = 12345
IP = 12.10.23.10
User = user1
}
how do i replace the contents after the = symbol using python ?
for example i want to replace with below contents.
The Test file contents are as below "Test1"{
Serial = 22330011
IP = 1.1.1.1
User = User_11
}
The contents after = symbols are not pre defined, hence substituting 12345 with 22330011 is not required here.
need a logic to find what is there after = symbol and replace it with the user defined value.
Lets say i have above data in temp.txt
file=open('temp.txt','r')
data=file.readlines()
outdata=[]
for line in data:
try:
lhs,rhs=line.split('=')
rhs=input()
outdata.append('='.join([lhs,' '+rhs,'\n']))
except:
outdata.append(line)
file.close()
file=open('temp.txt','w')
for line in outdata:
file.write(line)
This code read from the file and ask the input from user for rhs and updates in the file again
I am making a simple note-taking app. i want to save the contents of the entry box, save it to a txt file and when the program is next loaded, i want the box to read the file and contain the data. it works apart from the annoying brackets that appear in the text box. the brackets are not in the txt file. any help would be appreciated. (Sorry I use pretty random variable names)
import tkinter as tk
import os
from os import system
root=tk.Tk()
def yes():
charm = death.get("1.0", tk.END)
if (os.path.exists('charm.txt')):
moder = open('charm.txt','w')
moder.write(charm)
moder.close()
else:
moder = open('charm.txt','w+')
moder.write(charm)
moder.close()
print(charm)
death=tk.Text(root, height=5, width=50)
death.pack()
save=tk.Button(root, text='save', command = yes)
save.pack()
if (os.path.exists('charm.txt')):
drug = open('charm.txt','r')
note = (drug.readlines())
drug.close()
note = str(note)
print(note)
death.insert("1.0" ,note)
tk.mainloop()
Change:
note = (drug.readlines())
To:
note = drug.read()
This will fix your problem, as readlines() returns a list.
So I have a simple reddit bot set up which I wrote using the praw framework. The code is as follows:
import praw
import time
import numpy
import pickle
r = praw.Reddit(user_agent = "Gets the Daily General Thread from subreddit.")
print("Logging in...")
r.login()
words_to_match = ['sdfghm']
cache = []
def run_bot():
print("Grabbing subreddit...")
subreddit = r.get_subreddit("test")
print("Grabbing thread titles...")
threads = subreddit.get_hot(limit=10)
for submission in threads:
thread_title = submission.title.lower()
isMatch = any(string in thread_title for string in words_to_match)
if submission.id not in cache and isMatch:
print("Match found! Thread ID is " + submission.id)
r.send_message('FlameDraBot', 'DGT has been posted!', 'You are awesome!')
print("Message sent!")
cache.append(submission.id)
print("Comment loop finished. Restarting...")
# Run the script
while True:
run_bot()
time.sleep(20)
I want to create a file (text file or xml, or something else) using which the user can change the fields for the various information being queried. For example I want a file with lines such as :
Words to Search for = sdfghm
Subreddit to Search in = text
Send message to = FlameDraBot
I want the info to be input from fields, so that it takes the value after Words to Search for = instead of the whole line. After the information has been input into the file and it has been saved. I want my script to pull the information from the file, store it in a variable, and use that variable in the appropriate functions, such as:
words_to_match = ['sdfghm']
subreddit = r.get_subreddit("test")
r.send_message('FlameDraBot'....
So basically like a config file for the script. How do I go about making it so that my script can take input from a .txt or another appropriate file and implement it into my code?
Yes, that's just a plain old Python config, which you can implement in an ASCII file, or else YAML or JSON.
Create a subdirectory ./config, put your settings in ./config/__init__.py
Then import config.
Using PEP-18 compliant names, the file ./config/__init__.py would look like:
search_string = ['sdfghm']
subreddit_to_search = 'text'
notify = ['FlameDraBot']
If you want more complicated config, just read the many other posts on that.