I'm currently trying to create program that allows a user to view pictures of a shirt the user selects combined with different pants.
The program contains a directory filled with pictures of shirts, aswell as one of pants.
The user selects a shirt from a DropDown-menu, and the program then generates, saves, and displays the all possible combinations created using the shirt.
To accomplish this I'm using Tkinter & PIL (Pillow).
Here's my problem: When the user edits the DropDown-menu, and selects another shirt, I want the program to generate new images using THAT shirt, and replace the old images currently displayed.
I've read answers to similar questions, and some suggest a setter and getter, to detect and call a function when a variables' value is changed. I'm not quite sure I understand how it works, and definetly not how to implement it into my code. The function I want to call is inside a nested loop. Does that make any difference in this context?
Here is the code. The generateImage()function is a placeholder for the many rows of code that acutally generate the images.
To detect when the selected option from the DropDown-menu is changed, I use variable.trace.
shirtcolors = ["blue", "red", "green"]
def ChosenImage(*args):
chosen_image = variable.get()
print("value is: " + chosen_image)
selectedimage = ""
if chosen_image == "blue":
selectedimage = "C:/User/Desktop/OutfitGenerator/shirts/IMG_0840.jpg"
elif chosen_image == "red":
selectedimage = "C:/User/Desktop/OutfitGenerator/shirts/IMG_0850.jpg"
elif chosen_image == "green":
selectedimage = "C:/User/Desktop/OutfitGenerator/shirts/IMG_0860.jpg"
return selectedimage
DropdownList = tk.OptionMenu(frame, variable, *shirtcolors)
DropdownList.pack()
variable.trace("w", callback=ChosenImage)
shirtslist = [ChosenImage()]
pantsdirectory= "C:/User/Desktop/OutfitGenerator/pants"
pantslist = [os.path.abspath(os.path.join(pantsdirecotry, h)) for h in os.listdir(pantsdirecotry)]
for i in shirtslist:
for j in pantslist:
def generateImage(file1, file2):
My problem is that i can't figure out how to make the program run the code below the variable.trace line again. When a callback is sent to ChosenImage I want it to also continue the rest of the code, now using the new selectedimage value. However the continuation of the code cannot happen until the callback has reached the ChosenImage function, and it has changed its value.
My problem is that i can't figure out how to make the program run the
code below the variable.trace line again. When a callback is sent to
ChosenImage I want it to also continue the rest of the code, now using
the new selectedimage value.
This is the wrong way of thinking. Your callback is the thing that should generate the combinations/images - your callback shouldn't return anything, it should only have side-effects:
import tkinter as tk
class Application(tk.Tk):
def __init__(self, *args, **kwargs):
tk.Tk.__init__(self, *args, **kwargs)
self.title("Window")
self.geometry("256x64")
self.resizable(width=False, height=False)
self.shirt_colors = ["blue", "red", "green"]
self.pants_colors = ["brown", "black"]
self.drop_down_var = tk.StringVar(self)
self.menu = tk.OptionMenu(self, self.drop_down_var, *self.shirt_colors)
self.menu.pack()
self.drop_down_var.trace("w", callback=self.on_change)
def on_change(self, *args):
# Everytime the selection changes, generate combinations
shirt_color = self.drop_down_var.get()
for pant_color in self.pants_colors:
print("{} shirt with {} pants".format(shirt_color, pant_color))
def main():
Application().mainloop()
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Related
I'm working on a small project and I'm having issues retrieving the values stored in combo boxes. The program has a "plus" button that creates additional boxes beneath the existing ones. They are created by calling a "create" function that makes a new instance of the ComboBox class, where the box is created and put onto the screen. A separate "submit" function is then supposed to loop through and retrieve all of the box values and store them in a list. My main flaw is that I used data in the variable names, but I have no clue how else to do this in this scenario. Does anyone have an alternative solution?
(there are some off screen variables that are show used here as parameters, but there are definitely not the source of the issue)
class ComboBox:
def __init__(self, master, counter, fields):
self.master = master
self.counter = counter
self.fields = fields
self.field_box = ttk.Combobox(width=20)
self.field_box["values"] = fields
self.field_box.grid(row=counter + 1, column=0, pady=5)
def get_value(self):
value = self.field_box.get()
return value
def create():
global entry_counter
name = "loop"+str(entry_counter-1)
name = ComboBox(window, entry_counter, fields)
values.append(name.get_value())
entry_counter += 1
def submit():
for i in range(1, entry_counter):
name = "loop" + str(entry_counter-1)
values.append(name.get_value())
For example, if I created 2 boxes and selected the options "test1" and "test2" I would want the my values list to contain ["test1, "test2"]
Not sure I understand the question right, but I guess you are asking about how to loop throw all instances of ComboBox. You can just create an global array, append new instance into it in create() method:
comboboxes = []
def create():
...
comboboxes.append(new_instance)
def submit():
for combobox in comboboxes:
...
You're on the right track with .get(). I believe your solution is that your get_value function also needs an event parameter:
def get_value(self, event):
value = self.field_box.get()
return value
See the following:
Getting the selected value from combobox in Tkinter
Retrieving and using a tkinter combobox selection
--UPDATE:
I changed
variable=self.optionVal.get()
to
variable=self.optionVal
But nothing changed.Also I wonder why it automatically call self.selected while compiling?
----Original:
I'm trying to get familiar with radiobutton, but I don't think I understand how radiobutton works. Here's a brief code for demonstration:
self.optionVal = StringVar()
for text, val in OPTIONS:
print(text,val)
radioButton = Radiobutton(self,
text=text,
value=val,
variable=self.optionVal.get(),
command = self.selected())
radioButton.pack(anchor=W)
def selected(self):
print("this option is :"+self.optionVal.get())
In my opinion this should work like once I choose certain button, and it prints out "this option is *the value*", however now what it does is once compiled, it prints out everything, and the self.optionVal.get() is blankspace, as if value wasn't set to that variable.
I wonder what happens to my code,
Many thanks in advance.
AHA! I beleive I've figured it out. I had the exact same issue. make sure you are assigning a master to the IntVar like self.rbv=tk.IntVar(master) #or 'root' or whatever you are using):
import Tkinter as tk
import ttk
class My_GUI:
def __init__(self,master):
self.master=master
master.title("TestRadio")
self.rbv=tk.IntVar(master)#<--- HERE! notice I specify 'master'
self.rb1=tk.Radiobutton(master,text="Radio1",variable=self.rbv,value=0,indicatoron=False,command=self.onRadioChange)
self.rb1.pack(side='left')
self.rb2=tk.Radiobutton(master,text="Radio2",variable=self.rbv,value=1,indicatoron=False,command=self.onRadioChange)
self.rb2.pack(side='left')
self.rb3=tk.Radiobutton(master,text="Radio3",variable=self.rbv,value=2,indicatoron=False,command=self.onRadioChange)
self.rb3.pack(side='left')
def onRadioChange(self,event=None):
print self.rbv.get()
root=tk.Tk()
gui=My_GUI(root)
root.mainloop()
try running that, click the different buttons (they are radiobuttons but with indicatoron=False) and you will see it prints correctly changed values!
You're very close. Just take out the .get() from self.optionVal.get(). The Radiobutton constructor is expecting a traced variable, you're giving it the result of evaluating that variable instead.
You need to:
Remove the .get() from the variable=self.optionVal argument in the constructor the button. You want to pass the variable, not the evaluated value of the variable; and
Remove the parenthesis from command=self.selected() and use command=self.selected instead. The parenthesis says "call this function now and use the return value as the callback". Instead, you want to use the function itself as the callback. To better understand this, you need to study closures: a function can return a function (and, if that was the case, that would be used as your callback).
EDIT: A quick reminder, also: Python is not compiled, but interpreted. Your callback is being called while the script is being interpreted.
def view(interface):
choice = interface.v.get()
if choice == 0:
output = "0"
elif choice == 1:
output = "1"
elif choice == 2:
output = "2"
elif choice == 3:
output = "3"
else:
output = "Invalid selection"
return tk.messagebox.showinfo('PythonGuides', f'You Selected {output}.')
class Start:
def __init__(self):
self.root = tk.Tk()
self.root.geometry('500x500')
self.root.resizable(False, False)
self.root.title('find out the degree of severity')
self.v = tk.IntVar()
dolori_ossa = {"nessun dolore": 0,
"dolori articolari": 1,
"frattura composta": 2,
"frattura scomposta": 3}
for (txt, val) in dolori_ossa.items():
tk.Radiobutton(self.root,
text=txt,
variable=self.v,
value=val,
command=lambda:view(self)
).pack()
So I want to display a label if someone tries to click play and there is no save file made yet. Then I want it to fade out. The while loop works, reducing the value of alpha to 0. And it displays the label as long as I don't have the self.remove_widget(no_save) added in but then it just stays as a solid label. Any help would be appreciated. Or is there an easier way to do this?
class StartMenu(Screen):
def check_save(self):
global save_state
if save_state == None:
color = (0,1,0,1)
while color[3] > 0:
no_save = Label(text='No save file found. Please press New Game', color=color)
self.add_widget(no_save)
color = color [:3] + (color[3] - (.1),)
time.sleep(.1)
self.remove_widget(no_save)
Rather than doing the fade out yourself, why not use the built in Animation functionality? Try something like this. I would also suggest moving save_state from the global realm to your class, and instead of creating and destroying the label every run, I would create at initialization and simply hide or show it as it becomes necessary.
class StartMenu(Screen):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.save_state = None
no_save = Label('No save file found. Please press new game.', hidden=True)
self.add_widget(no_save)
def check_save(self):
if not self.save_state:
self.no_save.hidden = False
def hide_label(w): w.hidden = True
Animation(opacity=0, duration=1, on_complete=hide_label).start(self.no_save)
Quick shoutout to zeeMonkeys for pointing out the Animation solution in the comments before I did.
hey back again with the same code, well edited so it works better. anyway trying to add the button input into the array and that works. what doesn't work is the fact every time i call the function do() the values reset due to them being local. i tried to fix this by making it global(within the class) using the self.store array. this didn't seem to fix the problem so if someone could help would be much appreciated here is the relevant code
def __init__(self,master):#is the master for the button widgets
self.count=0
self.store=["0"]
frame=Frame(master)
frame.pack()
self.addition = Button(frame, text="+", command=self.add)#when clicked sends a call back for a +
self.addition.pack()
self.subtraction = Button(frame, text="-", command=self.sub)#when clicked sends a call back for a -
self.subtraction.pack()
self.equate = Button(frame, text="=", command=self.equate)#when clicked sends a call back for a =
self.equate.pack()
self.one = Button(frame, text="1", command=self.one)#when clicked sends a call back for a -
self.one.pack()
def add(self):
self.do("+")
self.count=self.count+1
def sub(self):
self.do("-")
self.count=self.count+1
def equate(self):
self.do("=")
def one(self):
self.do("1")
self.count=self.count+1
def do(self, X):#will hopefully colaborate all of the inputs
cont, num = True, 0
strstore="3 + 8"#temporarily used to make sure the calculating works
self.store=["2","1","+","2","3","4"]#holds the numbers used to calculate.
for num in range(1):
if X == "=":
cont = False
self.store[self.count]=X
print(self.store[self.count])
print(self.store[:])#test code
if cont == False:
print(self.eval_binary_expr(*(strstore.split())))
self.store=["2","1","+","2","3","4"]
If you initialize it this way in the do function, self.store will be reset to ["2","1","+","2","3","4"] every time you call do(X)
Initialize it outside of the do function if you don't want it to be overwritten.
But if you want to add a value to a list, use append(), extend, or += operator:
self.store+=["2","1","+","2","3","4"]
(if you want it to be done only once, do it in the constructor, __init__ function!)
also,
self.store[self.count]=X
If you try to append to the END of the list self.store, you should just do:
self.store.append(X)
This way, you won't need to count anything, with the risk of forgetting an incrementation and replacing a value by X instead of appending X.
As said above, range(1), it's 0...
Let's do it another way:
def do(self, X):
cont, num = True, 0
liststore=['3', '+', '8']#splitting your string.
#initialize str.store elsewhere!
if X == "=":
cont = False
self.store.append("X")
print(self.store[-1])#getting the last
print(self.store)#the same as self.store[:]
if cont == False:
print(self.eval_binary_expr(*(liststore)))
Simpler, and probably better.
Last thing: in Python, you are usually working with lists (like self.store), not arrays (which come from the module array)
I'm using Zelle Graphics library and I'm having trouble replacing graphics objects (which, in this case, happens to be text objects).
Here's the code:
from Graphics import *
winName = "Window"
win = Window(winName,600,500)
win.setBackground(Color('silver'))
title = Text((300,20),"Zack's Flash Card Maker")
title.draw(win)
p1 = Rectangle((50, 100),(550,400))
p1.setFill(Color("black"))
p1.draw(win)
class FlashCard:
def __init__(self):
self.commands = {'addQuestion':self.addQuestion,'startGame':self.startGame}
self.stack = []
self.questions = {}
self.questionAnswered = False
self.questionsCorrect = 0
self.questionsIncorrect = 0
def addQuestion(self):
question = ' '.join(self.stack)
self.stack = []
answer = input(question)
self.questions[question] = answer
def startGame(self):
for question in self.questions:
if(self.questionAnswered == False):
answer=input(question)
questionText = Text((300,150),question)
questionText.setFill(Color("white"))
questionText.draw(win)
if(answer == self.questions[question]):
questionAnswer = Text((300,200),answer + " is correct!")
questionAnswer.setFill(Color("green"))
questionAnswer.draw(win)
self.questionsCorrect = self.questionsCorrect + 1
continue
else:
questionAnswer = Text((300,200),answer + " is incorrect. Study this one.")
questionAnswer.setFill(Color("red"))
questionAnswer.draw(win)
self.questionsIncorrect = self.questionsIncorrect + 1
continue
def interpret(self,expression):
for token in expression.split():
if token in self.commands:
operator = self.commands[token]
operator()
else:
self.stack.append(token)
i = FlashCard()
i.interpret('What is your dog\'s name? addQuestion')
i.interpret('What is your favorite thing to do? addQuestion')
i.interpret('startGame')
This is essentially a mini flash card program I'm making. It takes the interpret commands at the bottom and executes them based on the dictionary in the FlashCard class. It basically works: it does the correct text objects. However, text begins to overlap other text objects because it re-draws. I've tried moving the .draw function all over, but it either doesn't appear at all or it overlaps.
Anyone have any suggestions? I want the text to replace for each new flashcard question.
Thanks!
there's an undraw() command that you need to use if you want to make something invisible. I'd recommend placing it right before your continue statements. It's used like
questionText.undraw()
questionAnswer.undraw()
Alternatively, you can use the del command to get rid of each questionText/questionAnswer instance when you're done with it. That's probably a better option since you're actually freeing up the memory that way instead of storing data and not doing anything with it.
You can use setText method to change the text.
example:
string = Text(Point(1, 1), 'original string')
sting.setText('new string')