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

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

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)

Tkinter replace line in note pad

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()

Parsing a dictionary in Python to my current table

I have a table that contains a few categories and two of them are: mac address and device name. I had a the list of my mac address written in my code (hardcoded) with their corresponding device names (ie deviceDict['00:00:00:00:00:00']= name)
Now, I passed those mac addresses and device names to a text file to be read from that same Python code and parse it onto my table. The code currently recognizes the text file but it is not parsing that information onto the table.
Here is the code:
# File: WapLogParser.py
# Desc: Parses a WAP log file and pulls out information relating to connected clients
# Usage: python WapLogParser.py [file glob]
import re
import sys
import glob
import os
deviceDict = dict()
# Base table for storing client info
# All names must match what is in the Wap Log file
# Exceptions: Date, Wap Name, Device Name - which are provided outside of the result parsing
table = [["Ssid", "Vlan", "Mac Address", "Connected Time", "Ip Address", "Rssi", "Date", "Wap Name", "Device Name"]]
def ParseResult(result, date, wapName):
lines = result.split('\n')
lines = list(filter(None, lines))
# Any useful info will be at least 2 lines long
if len(lines) == 1:
return
# create empty row
data = [""] * len(table[0])
# for each item in the result place it in the correct spot in the row
for line in lines:
if line != "":
# Parse the key/value pair
m = re.match(r"(.*):\s\.*\s?(.*)", line)
if m is not None:
for idx in range(len(table[0])):
if table[0][idx].lower() == m[1].lower():
data[idx] = m[2]
else:
break
# Remove the '(dBm)' from the RSSI value
data[5] = data[5].split()[0]
# Append WAP specific items to row
data[6] = date
data[7] = wapName
data[8] = GetDeviceName(data[2].upper())
# Add row to table
table.append(data)
def ParseFile(path):
with open(path) as f:
lines = f.readlines()
result = ""
command = ""
date = ""
# WAP name is always on the first line 16 characters in with 4
# unnecessary characters trailing
wapName = lines[0].strip()[16:-4]
for line in lines:
line = line.strip()
# Is an issued command?
if line.startswith("/#"):
if command != "":
ParseResult(result, date, wapName)
command = ""
# reset the result for the new command
result = ""
m = re.match(r"^/#.*show\sclient.*stats$", line)
if m is not None:
command = line
# Anything that is not a command add to the result
else:
result += line + "\n"
# Do we have the date?
if line.startswith("Current date:"):
date = line.replace("Current date: ", "")
# Print output to stderr
def eprint(*args, **kwargs):
print(*args, file=sys.stderr, **kwargs)
# Print a 2d array in a csv format
def PrintAsCsv(table):
for row in table:
print(",".join(row))
def Main():
InitDeviceDict()
numArgs = len(sys.argv)
for filename in glob.iglob(sys.argv[numArgs - 1], recursive=True):
# Globs get directories too
if os.path.isfile(filename):
eprint("Parsing " + filename)
try:
ParseFile(filename)
except Exception as e: # Mainly for if we see a binary file
eprint("Bad file: " + e)
# Print in a format we can use
PrintAsCsv(table)
def GetDeviceName(macAddress):
if macAddress in deviceDict:
return deviceDict[macAddress]
manufacturerPart = macAddress[:8]
if manufacturerPart in deviceDict:
return deviceDict[manufacturerPart]
return 'Unknown Device'
def InitDeviceDict():
with open('try.txt','r') as fo:
for line in fo:
deviceDict = {}
line = line.split(',')
macAddress = line[0].strip()
manufacturerPart = line[1].strip()
if macAddress in deviceDict:
deviceDict[macAddress].append(manufacturerPart)
else:
deviceDict[macAddress]=(manufacturerPart)
print(deviceDict)
# entry point
# script arguments:
# WapLogParser.py [file glob]
if __name__ == "__main__":
Main()
The issue is on the functions GetDeviceName and InitDeviceDict. When I run the code and then a batch file to display my info on excel, I keep getting "unknown device" (as if it is not recognizing the mac address I entered to produce the device name)
Any way I can correct this? Thank you
The deviceDict that is populated in InitDeviceDict is not the global deviceDict. You are only modifying a function-local dictionary (and resetting it every line as well). Remove deviceDict = {} from that function and, at the top of the function use global deviceDict to declare that you are modifying the global.
def InitDeviceDict():
global deviceDict
with open('try.txt','r') as fo:
for line in fo:
line = line.split(',')
macAddress = line[0].strip()
manufacturerPart = line[1].strip()
if macAddress in deviceDict:
deviceDict[macAddress].append(manufacturerPart)
else:
deviceDict[macAddress]=[manufacturerPart]

Append and replace objects in one string

I'm writing a text encoder/crypter (all by myself) and i can't understand how to append and replace characters in the string :-/
The code:
import os, sys, random
dig = 0
text_encoded = ""
text = ""
try:
if os.path.isfile(sys.argv[1]) == True:
with open(sys.argv[1], "r") as text:
text = text.readlines()
except:
pass
if text == "":
print("Write the text to encode")
text = input()
text = text.split()
for _ in range(len(text)):
text_encoded = text[dig].replace("qwertyuiopasdfghjklzxcvbnm ", "mnbvcxzlkjhgfdsapoiuytrewq#")
dig = dig+1
print("Your encoded text is:\n"+text_encoded)
Here is some output:
Write the text to encode
lo lolo lol lol
Your encoded text is:
lol
If you can help me in any way, thank you :-)
If I'm getting you correctly, you want to replace q with m, w with n and so on. Try the following
import os, sys, random
dig = 0
text_encoded = ""
text = ""
try:
if os.path.isfile(sys.argv[1]) == True:
with open(sys.argv[1], "r") as text:
text = text.readlines()
except:
pass
if text == "":
print("Write the text to encode")
text = input()
mychars=list("qwertyuiopasdfghjklzxcvbnm ")
myencode=list("mnbvcxzlkjhgfdsapoiuytrewq#")
charmap=zip(mychars,myencode)
_map = dict(charmap)
encoded_text = ''.join(_map.get(c) for c in text)
print("Your encoded text is:\n"+encoded_text)
The strings in your question mention that you want to replace ' ' with #. If you do not want to do that, just remove the last characters from both of the above strings.
have two lists instead of strings like from_ = "abc".split() and to_ = "def".split()
look for your char in from_ and get the index, get the same index char from to_ and stitch it to a new sentence.
example:
from_ = "abc".split()
to_ = "def".split()
old_msg = "ab ab"
new_msg = ""
for each in old_msg.split():
new_msg = new_msg + to_[from_.index(each)]
Hope this helps, please add missing char handling and any other edge cases
Or you can use str.translate
import os, sys, random
from pathlib import Path
TEXT_MAP = ("qwertyuiopasdfghjklzxcvbnm ", "mnbvcxzlkjhgfdsapoiuytrewq#")
def main():
text = ''
if len(sys.argv) > 1:
fname = sys.argv[1]
p = Path(fname)
if p.is_file():
text = p.read_text().strip()
print(f'Text from {p} is: {text}')
if not text:
text = input("Write the text to encode: ").strip()
trantab = str.maketrans(*TEXT_MAP)
text_encoded = text.translate(trantab)
print("Your encoded text is:\n"+text_encoded)
if __name__ == '__main__':
main()

Converting this Python code into a visual GUI?

I have a python code that a friend made , as I have very small knowledge of python..
I want to convert it into a GUI as we will distribute the code as a program for it to be beginner-friendly .
anyways here's the code:
import time, os, sys
try:
if len(sys.argv) < 2:
fn = raw_input("Enter the name of the file you want to edit: ")
else: fn = sys.argv[1]
f = open(fn)
b = f.read()
for i in b[:300]:
print hex(ord(i))[2:],
f.close()
line = str(0x15c)+'-'+str(0x15f)
if len(sys.argv)<3:
hexcode = raw_input("3 bytes color hex number: ")
else: hexcode = sys.argv[2]
if not hexcode.startswith('0x'):
hexcode = '0x'+hexcode
hexstr = '0x'
start = int(line.split('-')[0])
end = int(line.split('-')[1])
for i in b[start:end]:
hexstr+=hex(ord(i))[2:]
ascii = ''
for i in range(2,len(hexcode),2):
char = chr(int(hexcode[i:i+2],16))
ascii+=char
b = b[:start]+ascii+b[end:]
for i in b[:300]:
print hex(ord(i))[2:],
except Exception, x:
print x
time.sleep(3)
finally:
f = open(fn,'wb')
f.write(b)
f.close()
Now I found this on a tutorial but don't know how to use it:
#simple GU0I
from Tkinter import *
root = Tk()
root.title("BreffHexReplace")
root.geometry("400x200")
app = Frame(root)
app.grid()
label = Label(app, text = "This is a label!")
label.grid()
root.mainloop()
Any help?
thanks!
also one more thing , in this code , after I type in the name or the replacor hex , it shows me a list of hex , how can I make it not shown?
thanks!
Because this program is so simple, you can try EasyGui( easygui.sourceforge.net/ ). To start, add import easygui as eg. This line loads the EasyGui module. Next, replace fn = raw_input("Enter the name of the file you want to edit: ") with fn = eg.fileopenbox(title = 'HexReplace', msg = 'Browse to the file you wish to edit'). This opens a box to browse to the wanted file. Also replace hexcode = raw_input("3 bytes color hex number: ") with hexcode = eg.enterbox(msg = '3 bytes color hex number', title = 'HexReplace'). This pops up an input box. Replace print x with eg.msgbox(title = 'HexReplace', msg = x). This shows a message box with the exception. The title argument is the window title. To remove the hex list, add between the imports and the try block: null = open(os.devnull, 'W's); oldstdout = system.stdout; sys.stdout = null
This will silence all print messages.

Categories