Setting a scrollbar to work with a treeview - python

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)

Related

Django - Saving to DB, CSV file without single quotes

I have been trying to save a CSV file with information to add to db. And, is necessary to remove the single quotes, and ")". I already tried doing the replace but, didn't worked.
Also, I am doing this by an admin view. I add the csv file with informations to create objects on my db. And, it's from multiple tables. I don't know if I am using the right code or logic for this.
def upload_csv(self,request):
form = CSVImportForm(request.POST, request.FILES)
if request.method == "POST":
csv_file = request.FILES['csv_upload']
file_data = csv_file.read().decode("utf-8")
csv_data = file_data.split("\n")
csv_data = file_data.replace("'", "")
try :
for x in csv_data:
fields = x.split(",")
print(fields)
create_hospital = {}
create_hospital['hospital_name'] = fields[0],
create_hospital['hospital_website'] = fields[1],
create_hospital['hospital_fiscalAddress'] = fields[2],
create_hospital['hospital_shippingAddress'] = fields[3],
create_hospital['hospital_region'] = fields[4],
create_hospital['country'] = fields[5],
create_hospital['hospital_contactPerson'] = fields[6],
create_hospital['hospital_contactPhone'] = fields[7],
create_hospital['hospital_contactEmail'] = fields[8],
create_hospital['hospital_ImageLogo'] = fields[9]
created_hospital = HospitalViewRoleForUsers.objects.create(**create_hospital)
create_users = {}
create_users['FKLab_User'] = fields[0],
create_users['user_type'] = "1",
create_users['email'] = fields[11],
create_users['password'] = BaseUserManager().make_random_password(8),
create_users['name'] = fields[10],
# create_users['FKLab_User'] = created_hospital.id
# create_users['user_type'] = "1"
# create_users['email'] = fields[14],
# create_users['password'] = BaseUserManager().make_random_password(8),
# create_users['name'] = fields[13],
# create_users['FKLab_User'] = created_hospital.id
# create_users['user_type'] = "1"
# create_users['email'] = fields[17],
# create_users['password'] = BaseUserManager().make_random_password(8),
# create_users['name'] = fields[16],
created_users = CustomUser.objects.bulk_create(create_users)
create_roles = {}
create_roles['user_id'] = created_users[0],
create_roles['roles'] = fields[12],
created_roles = RoleHospital.objects.create(create_roles)
except Exception as e:
print("%s", e)
data = {"form": form}
return render(request, "admin/csv_upload.html", data)
Things are being add, except the fact that it adds with single quote and parenthesis.
e.g. : ('salkdklas',)
Thank you.

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

Open File Dialog running twice repeatedly

I tried to open two different types of files with QFileDialog in PyQt5 for pandas dataframe but it open repeatedly twice for each files before executed. However, when I'm using specific file only 'filename' it will directly executed once.
It's opened twice using this code:
class dataframe(QWidget):
def __init__(self, parent=None):
super(dataframe, self).__init__(parent)
layout = QVBoxLayout(self)
canvas = mycanvas(self)
layout.addWidget(canvas)
self.btn3 = QPushButton("Plot")
self.btn3.clicked.connect(canvas.PlotChart)
layout.addWidget(self.btn3)
def input(self):
lasdata = QFileDialog.getOpenFileName(self, 'Open LAS', r'data/', "LAS files (*.las)")[0]
textdata = QFileDialog.getOpenFileName(self, 'Open Text', r'data/', "Text files (*.txt)")[0]
l = lasio.read(f"{lasdata}")
data = l.df()
data = data.replace('-999.00000', np.nan)
data.index.names = ['DEPT']
w = l.well.WELL.value
data['WELL'] = w
text = pd.read_csv(f"{textdata}", sep='\t')
text_unit = text['RU'].unique()
data_w = pd.DataFrame()
for i in range(len(text_unit)):
top = text.iloc[i]['D']
if i < len(text_unit) - 1:
bottom = text.iloc[i + 1]['D']
else:
bottom = int(round(data.tail(1).index.item()))
data_int = data.iloc[top:bottom, :]
data_int['INT'] = text.iloc[i]['RU']
data_w = data_w.append(data_int)
data = data_w
return w, data
def det(self, gr):
w, data = dataframe.input(self)
GR = data.iloc[:, gr]
conditions = [
(GR <= 60),
(GR >= 60)]
lit = ['A', 'B']
data['L'] = np.select(conditions, lit, default='Undefined')
return data
def calculation(self):
w, data = dataframe.input(self)
data = dataframe.det(self, 1)
data_well = pd.DataFrame()
data_int = pd.DataFrame()
F_w = pd.DataFrame()
Fa = pd.DataFrame()
text_unit = data['INT'].unique()
for i in range(len(text_unit)):
data_int = data.where(data['INT'] == text_unit[i]).dropna()
F_percent = data_int['L'].value_counts(normalize=True) * 100
F_percent = F_percent.sort_index()
F_percent['INT'] = text_unit[i]
F_percent = pd.DataFrame(F_percent).transpose()
F_w = F_w.append(F_percent)
F_w['W'] = w
Fa = Fa.append(F_w)
F_w = pd.DataFrame()
Fa = Fa.reset_index()
Fa = Fa.fillna(0)
return Fa
class mycanvas(FigureCanvas):
def __init__(self, parent=None, dpi=120):
self.fig = plt.Figure(dpi=dpi)
FigureCanvas.__init__(self, self.fig)
def PlotChart(self):
outputs = dataframe.calculation(self) # .where(Fa['W']==well)
int = outputs['INT'].unique()
self.axes = self.fig.add_subplot(111)
self.axes.set_title("AA")
outputs.plot.barh(x='INT', stacked=True, ax=self.axes)
self.axes.set_yticks(range(len('INT')), 'INT')
self.draw()
if __name__ == '__main__':
app = QApplication(sys.argv)
window = dataframe()
window.show()
sys.exit(app.exec_())
However, it's directly executed once with this code:
def Input(self):
lasdata = 'data/AA.las'
textdata = 'data/AATEXT.txt'
l = lasio.read(lasdata)
data = l.df()
text = pd.read_csv(textdata, sep='\t')
Is there something wrong with File Dialog code, as with the lower code (direct name) it successfully executed once, but with the file dialog it opened twice before read the next codes. I need to make the GUI app so I need to use the file dialog.
This is part of the code with the two buttons:
self.btn1 = QPushButton("LAS File")
self.btn1.clicked.connect(self.las)
self.btn2 = QPushButton("Text File")
self.btn2.clicked.connect(self.text)
self.btn3 = QPushButton("Plot")
self.btn3.clicked.connect(canvas.PlotChart)
layout.addWidget(self.btn1)
layout.addWidget(self.btn2)
layout.addWidget(self.btn3)
def las(self):
self.lasfile = QFileDialog.getOpenFileName(self, 'Open LAS', r'data/', "LAS files (*.las)")[0]
def text(self):
self.textfile = QFileDialog.getOpenFileName(self, 'Open Text', r'data/', "Text files (*.txt)")[0]
def input(self):
lasdata = self.lasfile
textdata = self.textfile
l = lasio.read(f"{lasdata}")
data = l.df()
data = data.replace('-999.00000', np.nan)
data.index.names = ['DEPT']
w = l.well.WELL.value
data['WELL'] = w
text = pd.read_csv(f"{textdata}", sep='\t')
text_unit = text['RU'].unique()
I try to make it into two buttons but it can't be opened or exit fail to be executed.
below is one of the text format
WN RU D
AA SR 19
AA TF 50
AA PSU 1700

How to import values from excel with pandas into tkinter faster?

guys! How are you? I have this code below and I'm having this trouble with the insertData function. This function is used to enter values from an excel spreadsheet into the tkinter treeview using Pandas. It's almost all right, but it's too slow and I don't know how to fix it. If anyone could help me, I'd be very happy.
Thanks in advance!
from tkinter import *
import ttk
import openpyxl
import pandas as pd
nuScreen = Tk()
nuScreen.title("ContrasinSystem - Usuário Comum")
nuScreen.iconbitmap("logocontransin.ico")
book = openpyxl.load_workbook('Registros.xlsx')
sheet = book.sheetnames
sh = book.active.cell
#Contador de Linhas:
wb2 = openpyxl.load_workbook('Registros.xlsx')
sheet2 = wb2.worksheets[0]
rowCount = sheet2.max_row
v = []
#Design:
class main():
def __init__(self,tk):
for x in range (0,len(sheet)):
v.append(sheet[int(x)])
self.wb2 = openpyxl.load_workbook('Registros.xlsx')
self.sheet2 = self.wb2.worksheets[0]
self.row_count = self.sheet2.max_row
self.column_count = self.sheet2.max_column
self.nuFrame = Frame(nuScreen, width = 1500, height = 450)
self.nuFrame.pack()
self.img = PhotoImage(file="logocontransin.png")
self.w = Label(self.nuFrame, image = self.img)
self.w.img = self.img
self.w.place(x=65,y=150)
self.srchlbl = ttk.Label(self.nuFrame, text = "Buscar:")
self.srchlbl.place(x=25,y=75)
self.srchetr = ttk.Entry(self.nuFrame, width = 30)
self.srchetr.place(x=75,y=75)
self.treeview = ttk.Treeview(self.nuFrame)
self.treeview.place(x=300,y=75, width = 1100)
dataVector = []
def columnsName():
def Header():
self.columnVector = []
self.dataVector = []
teste = []
self.treeview.column("#0", width = 20)
self.columnHeader = pd.read_excel(r'Registros.xlsx', str(self.cmb.get()), header_only = True, nrows=0).columns
for a in self.columnHeader:
self.columnVector.append(a)
self.treeview.configure(columns = self.columnVector)
for b in self.columnHeader:
self.treeview.heading(str(b), text = str(b))
def insertData():
for m in range(rowCount):
self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()), skip_blank_lines=True, skiprows=0)
for l in self.dataValues:
dataVector.append(l)
self.treeview.insert("", "end",values = dataVector)
print(self.dataValues)
Header()
insertData()
self.cmbLbl = ttk.Label(self.nuFrame, text = "Assunto:")
self.cmbLbl.place(x=1200, y=325)
self.cmb = ttk.Combobox(self.nuFrame, values = v)
self.cmb.place(x=1250,y=325)
self.btncmb = ttk.Button(self.nuFrame, text = "Buscar", command = columnsName)
self.btncmb.place(x=1320,y=375)
nuScreen.geometry("1500x450")
main(nuScreen)
nuScreen.mainloop()
How many times do you want to open a excel file for reading?
def insertData():
for m in range(rowCount):
self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()),
skip_blank_lines=True, skiprows=0)
for l in self.dataValues:
dataVector.append(l)
self.treeview.insert("", "end",values = dataVector)
print(self.dataValues)
Should you instead omit the first loop?
def insertData():
self.dataValues = pd.read_excel(r'Registros.xlsx',str(self.cmb.get()),
skip_blank_lines=True, skiprows=0)
for l in self.dataValues:
self.treeview.insert("", "end",values = l)
print(self.dataValues)

PYMEL Maya UI crazyness

I'm having trouble with a script i judged simple, yet here I am! The thing is I have no real problem with the ACTUAL script, but with the Maya UI.
It seems I can't avoid the creation of multiple windows, nor delete it using deleteUI("nemeOfUI"). thats driving me crazy. I looked up on line and it seems I'm doing it alright and I just can't finde the answer.
Here the whole code.
Attention to lines 15 16 17 18, 110, 208.
I know the code isnt' the cleanest but its versin 1.2. Once it is working I'll do the cleaning! Thank you!
import pymel.core as pm
from functools import partial
import os.path
try:
pm.deleteUI(changeTexWindow)
except:
print''
global sizeChoice
def drawUi():
if (pm.window("ChangeTextureFiles_v1.2", query = True, exists = True)):
pm.deleteUI("ChangeTextureFiles_v1.2")
changeTexWindow = pm.window("ChangeTextureFiles_v1.2",
sizeable = False,
width = 300,
height = 175,
minimizeButton = False,
maximizeButton = False
)
uiTabs = pm.tabLayout(width = 300,
height = 175,
parent = changeTexWindow
)
uiColumn1 = pm.columnLayout("Change Texture Files",
rowSpacing = 5,
parent = changeTexWindow,
width = 300
)
uiColumn2 = pm.columnLayout("Help",
rowSpacing = 5,
parent = changeTexWindow,
width = 300
)
uiRowExtra = pm.rowLayout(numberOfColumns = 1, parent = uiColumn1, h = 2)
uiRow0 = pm.rowLayout(numberOfColumns = 3, parent = uiColumn1, h = 15)
pm.separator(style = "none", height = 10, width = 2, horizontal = False)
pm.text("Change texture...")
uiRow1 = pm.rowLayout(numberOfColumns = 3, parent = uiColumn1, h = 15)
uiRow2 = pm.rowLayout(numberOfColumns = 3, parent = uiColumn1, h = 15)
uiRow3 = pm.rowLayout(numberOfColumns = 3, parent = uiColumn1, h = 15)
options = pm.radioCollection(parent = uiRow1)
opt1 = pm.radioButton(parent = uiRow1, label = "From all objects in the scene", data=1)
opt2 = pm.radioButton(parent = uiRow2, label = "From only selected objects", data=2)
opt3 = pm.radioButton(parent = uiRow3, label = "From all objects in scene but selected", data=3)
options = cmds.radioCollection( options, edit=True, select=opt1 )
uiRow4 = pm.rowLayout(numberOfColumns = 3, parent = uiColumn1)
uiRow5 = pm.rowLayout(numberOfColumns = 2, parent = uiColumn1)
pm.text('Type the size of texture you want:', parent = uiRow5, annotation = "Enter values as '1,2 3...'. Check Help tab. ", width = 215)
sizeChoice = pm.textField(parent = uiRow5, width = 60, annotation = "Enter values as '1,2 3...'. Check Help tab. ")
uiRow6 = pm.rowLayout(numberOfColumns = 3, parent = uiColumn1)
allB = pm.button(label = "Apply", width = 115, command = partial(passValue, options, sizeChoice, 0))
selB = pm.button(label = "Apply and close", width = 115, command = partial(passValue, options, sizeChoice, 1))
otherB = pm.button(label = "Cancel", width = 54, command = "closeUi()")
helpTxt0 = pm.text("",parent= uiColumn2, height = 2)
helpTxt1 = pm.text("Created by Mendel Reis at", parent= uiColumn2, width = 300, height = 12)
helpTxt2 = pm.text("FACULDADE MELIES", parent= uiColumn2, width = 300,height = 12)
helpTxt3 = pm.text("www.melies.com.br", parent= uiColumn2, width = 300, height = 12)
helpTxt01 = pm.text(" ",parent= uiColumn2, height = 5)
helpTxt4 = pm.text("HOW TO USE:", parent= uiColumn2, width = 300, height = 12)
helpTxt5 = pm.text("Will change files thru naming convention:", parent= uiColumn2, width = 300, height = 12)
helpTxt6 = pm.text("file_name.SIZE.extension", parent= uiColumn2, width = 300, height = 12)
helpTxt7 = pm.text("Input the SIZE as you wish.", parent= uiColumn2, width = 300, height = 12)
helpTxt8 = pm.text("Only use . (DOT) to isolate the SIZE tag.", parent= uiColumn2, width = 300, height = 12)
pm.showWindow(changeTexWindow)
def passValue(options, sizeChoice, closeAfter, *args):
radioCol = cmds.radioCollection(options, query=True, sl=True)
selOption = cmds.radioButton(radioCol, query=True, data=True)
newSize = pm.textField(sizeChoice, query = True, tx = True)
print selOption
print newSize
if (selOption == 1):
changeAll(newSize)
elif (selOption == 2):
changeSelected(newSize)
elif (selOption == 3):
changeAllBut(newSize)
if (closeAfter):
try:
del sizeChoice
except:
print''
pm.deleteUI("ChangeTextureFiles_v1.2")
def changeAll(newSize):
allTex = pm.ls(type = "file")
notFound = [] #array for texture files without a size change match
for tex in allTex: #get info from texture file to be changed
path = tex.getAttr("fileTextureName") #get the full path of texture file
name = path.split("/")[-1].split('.')[0] #get the name of the file
size = path.split("/")[-1].split('.')[-2] #get the user specified, thru naming convention, texture file size info
extension = path.split("/")[-1].split('.')[-1] #get the texture file extension
if (size != newSize): #check if texture file needs to be changed
old = name + "." + size + "." + extension #concatenate the old name
new = name + "." + newSize + "." + extension #concatenate the new name
newTex = path.replace(old, new, 1) #create string for new fileTextureName
if (os.path.isfile(newTex)): #check if requered file exists
tex.setAttr("fileTextureName", newTex) #change the textureFileName
else:
notFound.append(name+'.' + extension) #create a log with failed attempts
def changeSelected(newSize):
objs = pm.selected()
for item in objs:
a = pm.listRelatives(item)[0]
b = pm.listConnections(a, type = "shadingEngine")
sgInfo = pm.listConnections(b, type='materialInfo')
fileNode = pm.listConnections(sgInfo[0], type='file')
textureFile = pm.getAttr(fileNode[0].fileTextureName)
name = textureFile.split("/")[-1].split('.')[0] #get the name of the file
print "NAME", name
size = textureFile.split("/")[-1].split('.')[-2] #get the user specified, thru naming convention, texture file size info
print "SIZE", size
extension = textureFile.split("/")[-1].split('.')[-1] #get the texture file extension
print "EXTENSION", extension
if (size != newSize): #check if texture file needs to be changed
old = name + "." + size + "." + extension #concatenate the old name
new = name + "." + newSize + "." + extension #concatenate the new name
newTex = textureFile.replace(old, new, 1) #create string for new fileTextureName
if (os.path.isfile(newTex)): #check if requered file exists
fileNode[0].setAttr("fileTextureName", newTex) #change the textureFileName
else:
print "Did not find a texture to replace. Check naming convention: enter size as '1K', '2K'..."
def changeAllBut(newSize):
allObjs = pm.ls(type = "mesh")
selection = pm.selected()
selObjs = []
for item in selection:
a = pm.listRelatives(item)[0]
selObjs.append(a)
for item in allObjs:
if item in selObjs:
allObjs.remove(item)
for item in allObjs:
a = item
b = pm.listConnections(a, type = "shadingEngine")
sgInfo = pm.listConnections(b, type='materialInfo')
fileNode = pm.listConnections(sgInfo[0], type='file')
textureFile = pm.getAttr(fileNode[0].fileTextureName)
name = textureFile.split("/")[-1].split('.')[0] #get the name of the file
print "NAME", name
size = textureFile.split("/")[-1].split('.')[-2] #get the user specified, thru naming convention, texture file size info
print "SIZE", size
extension = textureFile.split("/")[-1].split('.')[-1] #get the texture file extension
print "EXTENSION", extension
if (size != newSize): #check if texture file needs to be changed
old = name + "." + size + "." + extension #concatenate the old name
new = name + "." + newSize + "." + extension #concatenate the new name
newTex = textureFile.replace(old, new, 1) #create string for new fileTextureName
if (os.path.isfile(newTex)): #check if requered file exists
fileNode[0].setAttr("fileTextureName", newTex) #change the textureFileName
else:
print "Did not find a texture to replace. Check naming convention: enter size as '1K', '2K'..."
def closeUi():
try:
del sizeChoice
except:
print''
pm.deleteUI("ChangeTextureFiles_v1.2")
drawUi()
This question is a bit dated, but maybe an answer is still helpful:
The problem lies in the window objects name:"ChangeTextureFiles_v1.2". Windows etc. are Maya objects and they to not allow spaces or points. You can try it if you simply create a polycube and try to rename it to "polycube_v1.2".
For your window you can use the title flag instead:
WINNAME="CTexWin"
changeTexWindow = pm.window(WINNAME,
title = "ChangeTextureFiles_v1.2",
sizeable = False,
width = 300,
height = 175,
minimizeButton = False,
maximizeButton = False
)
And if you check for existence just use the WINNAME:
if pm.window(WINNAME, exists = True):
pm.deleteUI(WINNAME)

Categories