I'm working on looking up a cell value, and if that cell has nothing entered I want my code to do nothing, else I want to place a label on a Tkinter canvas, for some reason no matter what I do the label always ends up showing up, should the below code work?
##Grabbing the cell value from that indexed row and specific column, in this case pulling the value of indexed cell and column "Zixi Device"
Searched_Service_Row_Location_B = (excel_data_df.iloc[Searched_Service_Row_Location]["Zixi Device"])
Searched_Service_Row_Location_B_Value = (Searched_Service_Row_Location_B.values)
I am then taking the var Searched_Service_Row_Location_B_Value in an IF statment
if Searched_Service_Row_Location_B_Value == None:
pass
else:
Source1 = Label(Standard_window, text=Searched_Service_Row_Location_B_Value)
Source1.place(x=60, y=100)
The Source1 label always shows up, even though the cell value stored in the var has nothing entered in the excel document.
This seems to work the way I want it to
if str(Searched_Service_Row_Location_B_Value) in (None, "[nan]"):
pass
else:
Source1 = Label(Standard_window, text=Searched_Service_Row_Location_B_Value)
Source1.place(x=60, y=100)
Related
self.fm10 = tk.Frame(self.fm5)
self.fm10.grid(row=3,rowspan=3,columnspan=3,padx=5,pady=5)
self.treeview_box2 = Treeview(self.fm10,columns=('Assignment'))
self.style2 = Style()
self.style2.configure('Treeview',rowheight=70)
self.treeview_box2.heading('#0',text='Date')
self.treeview_box2.heading('Assignment',text='Assignment')
self.treeview_box2.column('#0',width=60,stretch=False)
self.treeview_box2.column('Assignment',width=175,stretch=False)
self.treeview_box2.pack(expand=True,pady=5)
my_cursor.execute('SELECT * FROM schedule')
self.schd = my_cursor.fetchall()
print(self.schd) ##A138MS Excel Test
self.count2 = 1
for s in self.schd:
self.treeview_box2.insert('',tk.END,text=s[0],values=(s[1]))
self.count2 += 1
In this code, I am trying to show the value s[1] on the treeview_box2 second column. The program is run successfully and stored into the database table. However the right side of value s[1] cannot be shown and only the left part is shown on the treeview_box2 table. May I ask is there any problems causing the value can be printed out but only the right part cannot be shown on the table?
The overall idea I have is to eventually add a button to my stickyNote nodes when I create them that when clicked would run a script that would give me a pop up window allowing me to change the value. Second idea was I had was for it just take the value within the default created and have it be empty rather than having the default values that appear on creation of "type note here".
I have tried to just set the value to ("") in my mind nothing would be in there, but the node still creates with the "type note here"
def setColor(R,G,B):
return int("%02x%02x%02x%02x" % (R,G,B,1),16)
def StickyNoteOverride():
nuke.thisNode()["tile_color"].setValue(setColor(R=(255*.298),G=(255*.298),B=(255*.298)))
nuke.thisNode()["note_font_size"].setValue(60)
nuke.thisNode()["note_font_color"].setValue(setColor(R=(255),G=(255*.624),B=(255*.0)))
nuke.thisNode()["note_font"].setValue("Deja Vu Sans Bold")
nuke.thisNode()["label"].setValue("")
####nuke.thisNode()['label'].setText("")
####nuke.thisNode()['label'].setText("1")
nuke.addOnUserCreate(StickyNoteOverride, nodeClass = "StickyNote")
My expected code so far does everything I want it too except for changing default on usercreate value to either nothing in the field, or to the value of 1 which I was using through the .setText to just get it to print anything in the field or change the field. .setText change was tried on an already created stickyNote to change the value. When running .setText("1), the value comes back with .getValue usage as having a value of 1 in the field. But the actual node did not change at all. And I am getting stuck in just changing this value of the label before I progress forward further with learning how to have it create a user defined button.
It just works for both variants - for string value "Lorem Ipsum Dolor..." and for empty string "":
def stickyNoteOverridden():
colour = int('%02x%02x%02x%02x' % (0,128,64,1),16) # Greenish
nuke.thisNode()["tile_color"].setValue(colour)
nuke.thisNode()["note_font_size"].setValue(60)
nuke.thisNode()["note_font_color"].setValue(100)
nuke.thisNode()["note_font"].setValue("Deja Vu Sans Bold")
# nuke.thisNode()["label"].setValue("Lorem Ipsum Dolor...")
# nuke.thisNode()["label"].setValue("")
nuke.addOnUserCreate(stickyNoteOverridden, nodeClass = "StickyNote")
nuke.createNode("StickyNote")
A key moment here is to use .createNode() command:
nuke.createNode("StickyNote")
Tested it in NukeX 11v3.5 NC on macOS Mojave 10.14.6.
I have an entry label where you type a name into. I want it to search through column 0 of the csv file. If that name exists, then it shall be displayed in a listbox that has already been created (this works fine) but if the name does not exist, I want to create a timed label ( the elif section). However, the code I have written displays the label when the name does AND doesn't exist.
with open('CLASSES.csv', 'rt')as f:
reader=csv.reader(f)
people=[]
for column in reader:
if column[0]==entry:
people.append(column[0:8])
namebox.delete(0,END)
nameslist=[x[0] for x in people]
for names in (nameslist):
namebox.insert(END, names)
elif column[0]!=entry:
INC=Label(master,text='User Does Not Exist',bg='#800000',fg='white')
INC.grid(row=2,column=3,columnspan=5,sticky='s')
def af():
INC.configure(fg='#800000')
INC.after(1000, af)
The if column[0] == entry: section works fine but I thought I would include it to make it easier to understand how the program works.
Any help would be great!
You are displaying the record for each entry.
Use a boolean typed variable to store if the entry was found. Initialize it with false before the loop begins. If an entry is equal, set it to true. After the loop check for this value and apply your if branch to it.
Pseudo code
search = "SomeEntryValue"
found = False
for line in open("csv-file", "r"):
if line[0] == search:
found = True
# Optional Tasks to be done here for each entry
if found:
# Display the Data
else:
# display the "User does not exist" message
I have the following code:
self.db='checks.db'
self.con = lite.connect(self.db)
self.cur = self.con.cursor()
self.q_oblig_initial='SELECT data_plirotees.rowid as rowid,recdate,bank,amount,dueto,gto,plirstatus FROM data_plirotees WHERE plirstatus=0 ORDER BY dueto ASC'
self.store_oblig = gtk.ListStore(int,str,str,str,str,str,bool)
self.cur.execute(q_oblig)
self.data_oblig=self.cur.fetchall()
for value in self.data_oblig:
if value[6]==0:
plir=False
elif value[6]==1:
plir=True
self.store_oblig.append([value[0],datetime.datetime.fromtimestamp(int(value[1])).strftime('%d/%m/%Y'),value[2],"%.2f" %(value[3]),datetime.datetime.fromtimestamp(int(value[4])).strftime('%d/%m/%Y'),value[5],plir])`
which gets data from a sqlite database and puts it in a liststore and,
rendererToggle.connect("toggled", self.on_cell_toggled)
column_toggle = gtk.TreeViewColumn("Καλύφθηκε", rendererToggle, active=1)
column_toggle.set_fixed_width(10)
treeView_oblig.append_column(column_toggle)
which has to show it in a column where true should show a checked toggle/checkbox and false should show un-checked.
Unfortunately this doesn't happen.
The checkbox needs not to be active (i don't want it to be able to toggle) but by clicking on the treeview row it opens a new window (where a checkbutton is checked or not accordingly). From that I understand that the true/false value is contained there somewhere but it is not presented visually.
Can someone show me where I'm wrong?
I didn't post the whole program 'cause it would be too big and perhaps misguiding...
self.store_oblig = gtk.ListStore(int,str,str,str,str,str,bool)
This line creates a GtkListStore where each column is of a different type. The columns are numbered from left to right, starting at 0:
self.store_oblig = gtk.ListStore(int,str,str,str,str,str,bool)
column number 0 1 2 3 4 5 6
You create your GtkTreeViewColumn with this:
column_toggle = gtk.TreeViewColumn("Καλύφθηκε", rendererToggle, active=1)
This says that the column's cell renderer should get the value of its active property from column 1 of the model (in this case, the list store). And the active property expects a bool.
But if you look back above, column 1 isn't a bool, but rather a string! So what you really wanted was active=6, not active=1. (Your code to add to the list store, on the other hand, seems correct.)
This is what the warning Warning: unable to set property 'active' of type 'gboolean' from value of type 'gchararray' gtk.main() is trying to tell you; gchararray is (one of) GLib's internal name(s) for a string.
I found this question, which was helpful to see the methodology, but I want to use their method without using a dictionary.
Basically, in Python I'm trying to use two optionmenu's from Tkinter where the first will contain the tabs of an excel document, and then the second will contain information that I've read from one of the columns once the tab has been selected from the first optionmenu. As I don't want to store and read every single tab prior, it seems much more efficient to just call the function to read the data once the tab was chosen rather than create a dictionary beforehand. Does someone know a way of doing this?
Here is what I have so far(excel_transfer is a self created library based off openpyxl- if you have further questions on what I'm doing feel free to ask, otherwise it doesn't seem necessary to go into it for the purposes of this question):
import Tkinter
from Tkinter import *
from ttk import Frame
import manipulate_excel
import openpyxl
from openpyxl import load_workbook
class GUI(Frame):
def read_tabs(self):
wkbk = load_workbook('file.xlsx')
sheets=wkbk.get_sheet_names()
return sheets
def read_columns(self):
sheet = self.tabs_var.get()
#if no value is selected, keep return a blank value
if(sheet == ''):
return ['']
else:
filepath = 'file.xlsx'
workbook = excel_transfer.workbook(filepath)
wb = workbook.open_existing_workbook()
ws = wb(sheet)
#step through the rows until a blank value is read
row = 1
current_row = 0
previous_row = 0
values = []
#read the column, and append values to the array
while current_row != None:
previous_row = current_row
row = row + 1
cell = 'A' + str(row)
current_row = workbook.read_new_cell(cell, ws)
if(current_row != None):
values.append(current_row)
#if there are no values, still return a single array value so it doesn't barf
if(values== []):
values= ['']
return values
def build_gui(self):
n = Notebook(self)
tab = Tkinter.LabelFrame(self, text='Tab')
n.add(tab, text='Tab')
n.pack()
self.tabsvar = StringVar()
self.tabsvar.set('')
self.valuesvar = StringVar()
self.valuesvar.set('')
self.list_of_tabs = self.read_tabs()
self.list_of_values = self.read_columns()
self.TAB_OPTION = OptionMenu(tab, self.tabsvar, *self.list_of_tabs)
self.TAB_OPTION.grid(row=0, column=0)
self.VALUES_OPTION = OptionMenu(tab, self.valuesvar, *self.list_of_values)
self.VALUES_OPTION.grid(row=1, column=0)
if __name__ == '__main__':
root = Tk()
app = GUI(root)
root.mainloop()
The first option works to find the tabs, but the problem I have is the read_column only happens when the GUI is initially opened, it remains a blank value. How would I make the self.list_of_values responsive to which tab is chosen in the first optionmenu? Can I use trace without a dictionary? I'm sure there's prettier ways of writing the code I did- I'm open to constructive criticism as there's always plenty to learn. Thank you for the help!
Ok, so I found the answer after continuing to work with it to help out anyone in future having the same problem.
I changed self.TAB_OPTION to:
self.TAB_OPTION(tab, self.tabsvar, *self.list_of_tabs, command=self.read_columns)
By adding this, I had to pass in a variable into self.read_columns, as adding the command automatically passes the value the user selected in the first optionmenu. So, I changed self.read_columns to:
def read_columns(self, board):
sheet = board
#sheet = self.tabs_var.get()
I also took out the line shown to be commented above, so it received the value that was selected in the first optionmenu from the TAB_OPTION rather than reading what is selected from the GUI. I also added in:
self.VALUES_OPTION['menu'].delete(0, 'end')
for item in values:
self.VALUES_OPTION['menu'].add_command(label=item)
at the end of the read_columns function so it would regenerate the values for the second optionmenu. It deletes all of the previous values, then adds each value that had been read from the excel in by iterating through the array. I no longer needed the return value at the end of the function.
I hope this helps other confused coders :)