Tkinter replace line in note pad - python

So I have an app that will export a number of fields into a notepad in a format. Works ok. However, I've tried doing the same thing but replacing an existing line in a notepad and I'm having problems. Rather than import it's giving me a 'results' not defined. I'm very new at this and any help would be great.
Below is the full code. If you comment line 16-29 and uncomment 32-44 it will work in a blank notepad. I'm trying to get the replace to work.
The user.txt file has a line that I want to replace everything inside the quotes:
Subject = "C=US, O=Testing Co, CN= Script Test, OU = OU Example, O = Example, L = Houston, S = Texas, C = US"
Code:
from tkinter import *
def save_info():
country_info = country.get()
organization_info = organization.get()
common_name = common.get()
org_unit = org.get()
location_info = location.get()
state_info = state.get()
results = (country_info,organization_info,common_name,org_unit,location_info,
state_info)
final = results
print(final)
file = open("user.txt", "r")
replacement = ""
# using the for loop
for line in file:
line = line.strip()
changes = line.replace("C=US, O=Testing Co, CN= Script Test, OU = OU Example, "
"O = Example, L = Houston, S = Texas, C = US", results)
replacement = replacement + changes
file.close()
# opening the file in write mode
fout = open("user.txt", "w")
fout.write(replacement)
fout.close()
#file = open("user.txt","w")
# file.write('"'"C:" + country_info + ",")
# file.write(" ")
# file.write("O:" + organization_info + ",")
# file.write(" ")
# file.write("CN:" + common_name +",")
# file.write(" ")
# file.write("OU:" + org_unit +",")
# file.write(" ")
# file.write("L:" + location_info +",")
# file.write(" ")
# file.write("S:" + state_info +'"')
# file.close()
app = Tk()
app.geometry("500x500")
app.title("Certificate Request Creation")
heading = Label(text="Certificate Request Creation",fg="black",bg="green",width="500",
height="3",font="10")
heading.pack()
country = StringVar()
organization = StringVar()
common = StringVar()
org = StringVar()
location = StringVar()
state = StringVar()
country_text = Label(text="Country Code:")
organization_text = Label(text="Organization")
common_text = Label(text="Common Name")
org_unit_text = Label(text="Organizational Unit")
location_info_text = Label(text="Location/City")
state_info_text = Label(text="State")
country_text.place(x=15,y=65)
organization_text.place(x=15,y=115)
common_text.place(x=15,y=165)
org_unit_text.place(x=15,y=215)
location_info_text.place(x=15,y=265)
state_info_text.place(x=15,y=310)
country_name_entry = Entry(textvariable=country,width="30")
organization_entry = Entry(textvariable=organization,width="30")
common_entry = Entry(textvariable=common,width="30")
org_unit_entry = Entry(textvariable=org,width="30")
location_info_entry = Entry(textvariable=org,width="30")
state_info_entry = Entry(textvariable=state,width="30")
country_name_entry.place(x=15,y=85)
organization_entry.place(x=15,y=135)
common_entry.place(x=15,y=185)
org_unit_entry.place(x=15,y=235)
location_info_entry.place(x=15,y=285)
state_info_entry.place(x=15,y=335)
button = Button(app,text="Create",command=save_info,width="30",height="2",
bg="grey")
button.place(x=150,y=400)
mainloop()

Related

storing output text in a tkinter textbox

im looking to output a list of text to both a text file as well as a tkinter textbox. Currently I have it working to print to a text file being held in the same folder. I would like this same list to be printed on screen into the outputToScreen textbox
From my research I think I am meant to use .insert(index , text) but I can not get this method to work. I have also seen some old code using a .set function but when I tried this I came across an error saying that textbox's don't have that method
#file -> gui.py
# IMPORT tkinter for GUI creation and import scripts for functions
from tkinter import *
from tkinter.ttk import *
import scripts
import customtkinter
windowDim = str(750)+'x'+str(600)
window = customtkinter.CTk()
window.title("INFO GENERATOR")
window.geometry(windowDim)
window.resizable(True, True)
# Modes: system (default), light, dark
customtkinter.set_appearance_mode("dark")
# Themes: blue (default), dark-blue, green
customtkinter.set_default_color_theme("customTkinterTheme.json")
outputToScreen = customtkinter.CTkTextbox(window , width=400 , height=200)
outputToScreen.place(x=200, y=300)
def popupmsg(msg):
popup = customtkinter.CTk()
popup.title("!")
label = customtkinter.CTkLabel(popup, text=msg,)
label.pack(side="top", fill="x", pady=10)
B1 = customtkinter.CTkButton(popup, text="Okay", command=popup.destroy)
B1.pack()
popup.mainloop()
# create main window
# window specs are 700 x 350 and window is not able to be resizeable
# CREATING USER CONTROLS
# each button will print a list of items (number of items will be come from the entry userValue)
userEntry = customtkinter.CTkEntry(window)
# userValue = int(userValue)
userValue = ""
userEntry.place(x=325, y=200)
userEntry.insert(0, userValue)
userValueLabel = customtkinter.CTkLabel(
window, text="ENTER AMOUNT OF RECORDS YOU WOULD LIKE").place(x=275, y=170)
label = customtkinter.CTkLabel(window, text="INFOMATION GENERATOR by Noah Mackay "
).pack()
def outputEmails(userValue):
# function receives the amount of records the user wants to print
# function will be called when email button is clicked
# this function will clear the output file and then read open it
# will call the generateEmail function from scripts.py file
# outputs the amount of records based on the user input in the entry text box
userValue = int(userEntry.get())
outputFile = scripts.generateEmail(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING WORKED")
def outputNames(userValue):
# function receives the amount of records the user wants to print
# function will be called when email button is clicked
# this function will clear the output file and then read open it
# will call the generateEmail function from scripts.py file
# outputs the amount of records based on the user input in the entry text box
userValue = int(userEntry.get())
outputFile = scripts.generateName(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING COMPLETED")
def outputCost(userValue):
userValue = int(userEntry.get())
outputFile = scripts.generateCost(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING COMPLETED")
def outputProduct(userValue):
userValue = int(userEntry.get())
outputFile = scripts.generateProduct(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.set(outputFile)
popupmsg("PRINTING COMPLETED")
def outputPhoneNumber(userValue):
userValue = int(userEntry.get())
outputFile = scripts.generatePhoneNumber(userValue)
file = open('output.txt', 'w').close()
file = open('output.txt', 'w')
file.write(str(outputFile))
outputToScreen.insert(0,outputFile)
popupmsg("PRINTING COMPLETED")
# creates 5 buttons each have their respective output function attached using command=
emailButton = customtkinter.CTkButton(window, text="EMAILS",
command=lambda: outputEmails(userValue)).place(x=5, y=40)
productButton = customtkinter.CTkButton(window, text="PRODUCTS",
command=lambda: outputProduct(userValue)).place(x=150, y=40)
phoneNumberButton = customtkinter.CTkButton(
window, text="PHONE NUMBERS" , command= lambda:outputPhoneNumber(userValue)).place(x=300, y=40)
costButton = customtkinter.CTkButton(window, text="PRICES",
command=lambda: outputCost(userValue)).place(x=450, y=40)
nameButton = customtkinter.CTkButton(
window, text="FIRST + LAST NAMES", command=lambda: outputNames(userValue)).place(x=600, y=40)
window.mainloop()
#file -> scripts.py
import random
def generateName(numberOfItemsNeed):
# opens 2 files. One containing first names and the other containing last names
firstNameFile = open('dataFiles\FirstNamesData.txt', 'r')
lastNameFile = open('dataFiles\LastNamesData.txt', 'r')
# builds values for the while statement and the return string
returnValue = ""
counter = 0
# builds the return string using a while loop and removing the newline character
# after each line from both files when being read
while counter < int(numberOfItemsNeed):
returnValue += str(firstNameFile.readline().strip("\n")
) + " " + str(lastNameFile.readline().strip("\n")) + "\n"
counter = counter + 1
# returns a list of "human" names in a single string divided by a newline character
return (returnValue)
def generateEmail(numberOfItemsNeed):
# opens a file containing a records of first names
firstNameFile = open('dataFiles\dictonary.txt', 'r')
counter = 0
# A list of commonly used email address suffixs
suffix = ['#gmail.com', '#gmail.ca', '#hotmail.com',
'#hotmail.ca', '#mail.com ', '#mail.ca', '#gov.ca']
returnValue = ""
while counter < int(numberOfItemsNeed):
returnValue += firstNameFile.readline().strip("\n") + \
str((random.randrange(0, 100))) + \
suffix[random.randrange(0, len(suffix))]+'\n'
counter = counter + 1
return (returnValue)
def generateCost(numberOfItemsNeed):
# generates a random item price in the inclusive range of 0.00$ to 1000.99$
counter = 0
cost = ""
while counter < int(numberOfItemsNeed):
cost += '$' + str(random.randrange(0, 1000)) + \
"." + str(random.randrange(0, 99)) + '\n'
counter = counter+1
return cost
def generateProduct(numberOfItemsNeed):
counter = 0
returnValue = ""
productList = open('dataFiles\itemData.txt', 'r')
while counter < int(numberOfItemsNeed):
returnValue += str(productList.readline()
).strip("\n") + str(generateCost(1))
counter = counter + 1
return (returnValue)
def generatePhoneNumber(numberOfItemsNeed):
counter = 0
returnValue = ""
while counter < int(numberOfItemsNeed):
firstNumber = str(random.randrange(100, 999))
secondNumber = str(random.randrange(1000, 9999))
thirdNumber = str(random.randrange(100, 999))
returnValue += firstNumber + "-" + secondNumber + "-" + thirdNumber + '\n'
counter = counter + 1
return (returnValue)
def shuffleFile(filePath):
lines = open(filePath).readlines()
random.shuffle(lines)
open(filePath, 'w').writelines(lines)
# shuffleFile('dataFiles\dictonary.txt')
Text widget indexes are strings of the form line.character with lines starting at 0 and characters starting at 1. So, to insert at the start you need to use the index "1.0", not 0. If you want to insert at the end you can use the special index "end". If the widget is empty, "1.0" and "end" yield identical results.
outputToScreen.insert("1.0", outputToFile)

my for loop doesn't work when i tried to make a user interface

I'm making a user interface but my for loop is not working. i wanted to say somthing when th username was alredy used butmy code yust skips the for loop and then append the username and password to the list. in the txt file stand in each line username;password
import tkinter as tk
from tkinter import *
root = Tk()
root.title("WRTS oefentoets")
root.geometry("735x355")
def sign():
userfile = open("users.txt", "a+")
users = list(userfile.readlines())
found = 0
for line in users:
parts = line.split(";")
if parts[0] == username.get():
found = 1
break;
if found == 1:
bestaatal.place(x= 300, y= 200)
else:
with open('users.txt', "a+") as file_object:
# Move read cursor to the start of file.
file_object.seek(0)
# If file is not empty then append '\n'
data = file_object.read()
if len(data) > 0:
file_object.write("\n")
# Append text at the end of file
file_object.write(username.get() + ";" + password.get())
username = Entry(root, bg = 'black', fg = 'magenta')
password = Entry(root, bg = 'black', fg = 'magenta')
signin = Button(root, bg = 'black', fg = 'magenta', text = 'sign up', command = sign, width = 7)
signin.place(x= 343, y= 181)
username.place(x=262.5, y= 135)
password.place(x=262.5, y= 157.5)
.readlines on a file in append mode starts reading from the end of that file
So, since from userfile you're only reading, just open it in read mode:
with open("users.txt", 'r') as userfile:
... # your code

Python program doesn't write in a file

The user gives input to the program and it should write it in a file There is a problem with uploading it to the txt file.
Plan = open("Plan.txt", "r")
content = Plan.read()
Plan_lista = content.split(",")
Przedmioty = []
Przedmioty = list(set(Plan_lista))
Przedmioty.remove("")
Plan.close()
#Dodawanie linków do listy
Linki = open("Linki.txt", "w+")
print("\n" + "Podaj Link do:")
a=0;
for i in range(len(Przedmioty)):
print (Przedmioty[a], end = "\r")
link = input(": ")
Linki.write(Przedmioty[a] + "," + link)
if ( a != len(Przedmioty)-1):
Linki.write(", ")
a+=1

Setting a scrollbar to work with a treeview

I'm attempting to add a scrollbar to a tree here in order to keep the data within view for the user, as the tree stretches offscreen(the window is limited at 1280x720). However, the scrollbar does not move it across. Here is the code:
self.treeFrame = ttk.Frame(self)
self.treeFrame.grid(row = 12,column = 0,columnspan = 1000,rowspan = 100)
self.tree = ttk.Treeview(self.treeFrame,height = 100, columns = ('name','purchaseprice','previousprices','listingprice','buyingformat','postage','fees','potprofit','offers','viewcount','sold','offertaken','username','dispatch','delivered','returned','relist','feedback'))
self.tree.heading('#0',text = 'saleID',anchor = 'w')
self.tree.heading('name',text = "Item Name",anchor = 'w')
self.tree.heading('purchaseprice',text = "Purchase Price",anchor = 'w')
self.tree.heading('previousprices',text = "Previous Prices",anchor = 'w')
self.tree.heading('listingprice',text = "Listing Price", anchor = 'w')
self.tree.heading('buyingformat',text = "Buying Format",anchor = 'w')
self.tree.heading('postage',text = "Postage",anchor = 'w')
self.tree.heading('fees',text = "Fees",anchor = 'w')
self.tree.heading('potprofit',text = "Potential Profit",anchor = 'w')
self.tree.heading('offers',text = "Best Offer",anchor = 'w')
self.tree.heading('viewcount',text = "Viewcount",anchor = 'w')
self.tree.heading('sold',text = "Sold?",anchor = 'w')
self.tree.heading('offertaken',text = "Offer Taken?",anchor = 'w')
self.tree.heading('username',text = "Username",anchor = 'w')
self.tree.heading('dispatch',text = "Dispatched?",anchor = 'w')
self.tree.heading('delivered',text = "Delivered?",anchor = 'w')
self.tree.heading('returned',text = "Returned?",anchor = 'w')
self.tree.heading('relist',text = "Relisted?",anchor = 'w')
self.tree.heading('feedback',text = "Feedback",anchor = 'w')
hsb = ttk.Scrollbar(self,orient = "horizontal")
self.tree.grid(row = 14,column = 0,sticky ='nsew')
hsb.grid(row = 11,column = 0,columnspan = 10,sticky = 'ew')
hsb.config(command = self.tree.xview)
Does anyone know how I would go about restricting the size of the tree in order to get it into a position where it can be scrolled across with in the bounds of the window?
Scrollbars need to be told what command to run when the user moves the scrollbar, and widgets need to know which command to run when it has been scrolled. You're not doing either of these.
For example, in your code you need to do both of these:
hsb.configure(command=self.tree.xview)
self.tree.configure(xscrollcommand=hsb.set)

PYQT: Set text of lineedit if an item in combobox is selected

My Question:
How can I fill the text in a lineedit with the 'employeeID' if the ADuser is selected?
What I am doing: I run a PS script from python, which gets me the ADusers, then I take the Output from the PS-Script (the AD-Users basically) and fill it into a Combobox (around 500 'items').
Python code(Edited):
# NOTE: this is not the full code, just the full code for solving the problem
def __init__(self):
super().__init__()
self.__initUI__()
def __initUI__(self):
self.vorgesetzter()
self.persnum_supervisor()
self.fill_the_combo_box()
self.Vorgesetzte.currentIndexChanged.connect(self.display_employee_id)
def fill_the_combo_box(self):
"""Filling the combo box with the names extracted from a file."""
subprocess.Popen(["powershell.exe", "C:\\Users\\User\\Desktop\\Get-ADUser.ps1"], stdout=subprocess.PIPE, universal_newlines=True, shell=True).communicate()
lines = open('C:\\Users\\User\\Desktop\\users.txt').readlines()
open('C:\\Users\\User\\Desktop\\newusers.txt', 'w').writelines(lines[3:])
with open("C:\\Users\\User\\Desktop\\newusers.txt", 'r', encoding='utf8') as f:
content = f.readlines()
for line in content:
tokens = line.split()
if len(tokens) < 2:
continue # <--- skip the empty line of the file
tostring = tokens[0] + " " + tokens[1] # <--- this is the full name
self.Vorgesetzte.addItems([tostring])
def display_employee_id(self):
"""Checking whether the currently selected combo box name has an employeeID stored in the file."""
with open("C:\\Users\\User\\Desktop\\users.txt", 'r', encoding='utf8') as f:
selected_name = self.Vorgesetzte.currentText()
content = f.readlines()
for line in content:
tokens = line.split()
if len(tokens) < 2:
continue
full_name = tokens[0] + " " + tokens[1]
employeeID = str(tokens[2]) if len(tokens)==3 else "no id found!" # <-- support for absence of employeeID in the file, put whatever string you like here
if selected_name == full_name:
self.persnum_supervisor.setText(employeeID)
break
def vorgesetzter(self):
"""Eingabefeld für den Vorgesetzten"""
self.Vorgesetzte = QComboBox(self)
self.Vorgesetzte.setEditable(True)
self.Vorgesetzte.completer()
font = self.Vorgesetzte.font()
font.setPointSize(9)
self.Vorgesetzte.setFont(font)
self.Vorgesetzte.setFixedSize(250, 20)
self.Vorgesetzte.move(150, 210)
self.VorgesetzteBlock = QLabel(self)
self.VorgesetzteBlock.move(10, 210)
self.VorgesetzteBlock.setText("Vorgesetzte/r:")
def personalnum_supervisor(self):
"""TEXTLINE FÜR PERSONALNUMMER SUPERVISOR"""
self.persnum_supervisor = QLineEdit(self)
self.persnum_supervisor.setMaxLength(20)
font = self.persnum_supervisor.font()
font.setPointSize(9)
self.persnum_supervisor.setFont(font)
regex = QRegularExpression('^\d\d\d\d\d\d')
validsuper_vis = QRegularExpressionValidator(regex)
self.persnum_supervisor.setValidator(validsuper_vis)
self.persnum_supervisor.move(750, 300)
self.persnum_supervisor.setFixedSize(250, 20)
self.persnum_supervisorBlock = QLabel(self)
self.persnum_supervisorBlock.move(500, 300)
self.persnum_supervisorBlock.setText("Personalnummer(Vorgesetzter):")
app = QApplication(sys.argv)
w = MainWindow()
sys.exit(app.exec_())
So what I need to do next is: If the AD-User is selected in the Combobox, I need to set the text in a lineedit with the AD-Users attribute of his 'employeeID'.
Powershell code below:
$s = "OU=,DC=,DC="
$User = Get-ADUser -Filter * -Properties name, employeeID -Searchbase $s |
Select-Object -Property name,employeeID
$User | Sort-Object -CaseSensitive | Out-File -Encoding utf8 C:\Users\USER\Desktop\users.txt
Users.txt file (I cant show you the names of our employees thats why I edited it a bit):
name employeeID
---- ----------
forename surname 110001
forename surname 110002
forename surname 110003
forename surname 110004
forename surname 110005
forename surname 110006
I appreciate any help how this might work !
Now that you store the employeeID in the file, it is easier to solve.
What I modified is shown in comments.
from PyQt5 import QtWidgets,QtGui,QtCore
import sys
import subprocess
class Widget(QtWidgets.QWidget):
def __init__(self,parent=None):
super(Widget,self).__init__(parent=None)
self.cbox = QtWidgets.QComboBox(self)
self.setGeometry(100,100,300,300)
self.fill_the_combo_box()
self.lineEdit = QtWidgets.QLineEdit(self)
self.lineEdit.setGeometry(100,100,100,100)
self.cbox.currentIndexChanged.connect(self.display_employee_id) # will trigger every time you select a new name in the combo box.
def fill_the_combo_box(self):
"""Filling the combo box with the names extracted from a file."""
subprocess.Popen(["powershell.exe", "C:\\Users\\USER\\Desktop\\Get-ADUser.ps1"], stdout=subprocess.PIPE, universal_newlines=True, shell=True).communicate()
lines = open('C:\\Users\\USER\\Desktop\\users.txt').readlines()
open('C:\\Users\\USER\\Desktop\\newusers.txt', 'w').writelines(lines[3:])
with open("C:\\Users\\USER\\Desktop\\newusers.txt", 'r', encoding='utf8') as f:
content = f.readlines()
for line in content:
tokens = line.split()
if len(tokens) < 2:
continue # <--- skip the empty line of the file
tostring = tokens[0] + " " + tokens[1] # <--- this is the full name
tostringcleared = tostring.replace("[", "").replace("'", "").replace('\\ufeff',"").replace("]", "").replace(",", "") #clear the strings from special characters
self.cbox.addItems([tostringcleared])
def display_employee_id(self):
"""Checking whether the currently selected combo box name has an employeeID stored in the file."""
with open("C:\\Users\\USER\\Desktop\\users.txt", 'r', encoding='utf8') as f:
selected_name = self.cbox.currentText()
content = f.readlines()
for line in content:
tokens = line.split()
full_name = tokens[0] + " " + tokens[1]
employeeID = str(tokens[2]) if len(tokens)==3 else "no id found!" # <-- support for absence of employeeID in the file, put whatever string you like here
if selected_name == full_name:
self.lineedit.setText(employeeID)
break
if __name__ == "__main__":
app = QtWidgets.QApplication(sys.argv)
widget = Widget()
widget.show()
sys.exit(app.exec_())
Two things to note:
Duplicates are not supported. If you have the same name several times but with different employeeID, the line edit will take the value of the first one encountered (or the last one if you remove the break). But if there are duplicates that's an issue with your file anyway.
Maybe you want to keep the headers we can skip the two first lines using this:
.
for n, line in enumerate(content):
if n<2:
continue

Categories