How to fix this Tkinter button bug - python

Whenever I run the program, the buttons show up however the images do not show and instead appear as a grey space. Also, all the buttons apart from the 'finish' button are unpressable (see the image attached).
def NoFood():
TotalCalories = NoBreakfast.calories
NoFoodOption = 1
def BoiledEggsFunct():
TotalCalories = BoiledEggs.calories + TotalCalories
def FriedEggsFunct():
TotalCalories = FriedEggs.calories + TotalCalories
def ScrambledEggsFunct():
TotalCalories = ScrambledEggs.calories + TotalCalories
def PoachedEggsFunct():
TotalCalories = PoachedEggs.calories + TotalCalories
def ToastFunct():
TotalCalories = Toast.calories + TotalCalories
def BaconFunct():
TotalCalories = Bacon.calories + TotalCalories
def CerealFunct():
TotalCalories = Cereal.calories + TotalCalories
def PorridgeFunct():
TotalCalories = Porridge.calories + TotalCalories
def FinishScreen():
FinishWindow = Toplevel()
if TotalCalories > 0 and TotalCalories < 1000:
HealthyLabel = Label(FinishWindow, text = "Congratulations, you are healthy!", font=("Comic Sans MS", 25), fg = "light green",
bg = "black")
HealthyLabel.grid(columnspan=10)
elif TotalCalories > 1000:
UnhealthyLabel = Label(FinishWindow, text = "Try to eat healthier tomorrow. See personalised advice", font=("Comic Sans MS", 25), fg = "yellow",
bg = "black")
UnhealthyLabel.grid(columnspan=10)
elif NoFoodOption == 1:
NoFoodLabel = Label(FinishWindow, text = "Not eating can be harmful to your health. See personalised advice", font=("Comic Sans MS", 25), fg = "red",
bg = "black")
NoFoodLabel.grid(columnspan=10)
else:
Error = Label(FinishWindow, text = "error", font=("Comic Sans MS", 25), fg = "red",
bg = "black")
NoFoodLabel.grid(columnspan=10)
BoiledEggsPhoto = PhotoImage(file="BoiledEgg.gif")
BoiledEggsButton = Button(FoodSelectionWindow, text="Boiled Eggs", command=BoiledEggsFunct, image=BoiledEggsPhoto, compound=LEFT, height=100, width = 200)
BoiledEggsButton.grid(column=1,row=3)
ScrambledEggsPhoto = PhotoImage(file="ScrambledEgg.gif")
ScrambledEggsButton = Button(FoodSelectionWindow, text="Scrambled Eggs", command=ScrambledEggsFunct, image=ScrambledEggsPhoto, compound=LEFT, height=100, width = 200)
ScrambledEggsButton.grid(column=2,row=3)
FriedEggsPhoto = PhotoImage(file="FriedEgg.gif")
FriedEggsButton = Button(FoodSelectionWindow, text="Fried Eggs", command = FriedEggsFunct, image=FriedEggsPhoto, compound=LEFT, height=100, width = 200)
FriedEggsButton.grid(column=3, row=3)
PoachedEggsPhoto = PhotoImage(file="PoachedEgg.gif")
PoachedEggsButton = Button(FoodSelectionWindow, text="Poached Eggs", command = PoachedEggsFunct, image=PoachedEggsPhoto, compound=LEFT, height=100, width = 200)
PoachedEggsButton.grid(column=1, row=4)
ToastPhoto = PhotoImage(file="Toast.gif")
ToastButton = Button(FoodSelectionWindow, text="Toast", command = ToastFunct, image=ToastPhoto, compound=LEFT, height=100, width = 200)
ToastButton.grid(column=2,row=4)
BaconPhoto = PhotoImage(file="Bacon.gif")
BaconButton = Button(FoodSelectionWindow, text="Bacon", command = BaconFunct, image=BaconPhoto, compound=LEFT, height=100, width = 200)
BaconButton.grid(column=3, row=4)
CerealPhoto = PhotoImage(file="Cereal.gif")
CerealButton = Button(FoodSelectionWindow, text="Cereal", command = CerealFunct, image=CerealPhoto, compound=LEFT, height=100, width = 200)
CerealButton.grid(column=1, row=5)
PorridgePhoto = PhotoImage(file="Porridge.gif")
PorridgeButton = Button(FoodSelectionWindow, text="Porridge", command = PorridgeFunct, image=PorridgePhoto, compound=LEFT, height=100, width = 200)
PorridgeButton.grid(column=2, row=5)
NoBreakfastPhoto = PhotoImage(file="NoBreakfast.gif")
NoBreakfastButton = Button(FoodSelectionWindow, text= "None", command = NoFood, image=NoBreakfastPhoto, compound=LEFT, height=100, width = 200)
NoBreakfastButton.grid(column=3, row =5)
EndScreen = Button(FoodSelectionWindow, text="Finish", command = FinishScreen, width=12)
EndScreen.grid(column=2,row=6)
Any suggestions? Thanks.

Related

prng,python, tkinter,need to change picture

I ran into this problem and don't know how to solve it.
When I press the "generate" button(self.gen), my picture 11 changes to picture 22.
BUT I need the image 11 to NOT change when the button is clicked and an error occurs(messagebox.showerror pops up) OR so that after closing the messagebox.showerror, picture 22 changes to 11
import tkinter
from tkinter import *
from tkinter import messagebox, scrolledtext
from PIL import Image, ImageTk
from random import randint
class App:
def __init__(self):
self.window = tkinter.Tk()
self.window.title("Генератор")
self.window['bg'] = '#FFF5EE'
self.window.geometry('660x550')
self.window.resizable(False,False)
self.lb1 = Label(self.window, text="Enter:", background='#FFF5EE', font = ("Comic Sans MS", 14))
self.lb1.grid(column=0, row=2)
self.lb2 = Label(self.window, text="min(1-999)",background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb2.grid(column=1, row=3)
self.lb3 = Label(self.window, text="max(1-999)", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb3.grid(column=1, row=4)
self.lb4 = Label(self.window, text="amount of numbers", background='#FFF5EE', font = ("Comic Sans MS", 12))
self.lb4.grid(column=4, row=3)
self.txt2 = Entry(self.window,width=10, borderwidth=3)
self.txt2.grid(column=2, row=3)
self.txt3 = Entry(self.window,width=10, borderwidth=3)
self.txt3.grid(column=2, row=4)
self.txt4 = Entry(self.window,width=10, borderwidth=3)
self.txt4.grid(column=5, row=3)
self.scrolltxt = scrolledtext.ScrolledText(self.window, width=30, height=3, borderwidth=7, state='disabled')
self.scrolltxt.grid(row=1, column=2, columnspan=3, padx=10, pady=10)
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.gen = Button(self.window, width = 15, text="Generate", command = lambda:[self.clicked1(), self.gen1()])
self.gen.grid(row=4, column=6)
self.canvas = tkinter.Canvas(self.window, height=230, width=230)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw', image = self.photo)
self.btn = Button(self.window, width = 15, text="Delete", command=lambda:[self.delete(),self.clicked2()])
self.btn.grid(column=6, row=5)
self.exit = Button(self.window, width = 15, text="Exit", command=lambda: [self.clicked3(), quit()])
self.exit.grid(column=6, row=6)
self.i = Button(self.window, width = 8,text = "i", font = ("Eras Bold ITC", 10) , command = self.inf)
self.i.grid(row = 0,column = 6)
self.window.mainloop()
def clicked1(self):
print("clicked1")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\22.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box
else:
messagebox.showerror("Error", "Якщо не рвешся у висоту, шишок не наб'єш.")
def delete(self):
self.txt4.delete(0, END)
self.txt3.delete(0, END)
self.txt2.delete(0, END)
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.config(state="disabled") # disable the text box
def clicked2(self):
print("clicked2")
self.image = Image.open("C:\\Users\\ПК\\OneDrive\\Рабочий стол\\лб1\\11.png")
self.photo = ImageTk.PhotoImage(self.image)
self.canvas.grid(row=0,column=4)
self.image = self.canvas.create_image(0, 0, anchor='nw',image=self.photo)
def clicked3(self):
messagebox.showinfo("Це Звірополіс. Будь-хто може бути будь-ким.", "Хто сказав, що неможливе недосяжне?! Пошкодуйте цього дивака.")
def inf(self):
messagebox.showinfo("Info", "Лисичка замахалась")
app = App()
is it possible to implement this through tkinter?
Change the command argument of self.gen to:
self.gen = Button(self.window, width = 15, text="Generate", command=self.gen1)
And move the call to clicked1() into the if block of gen1() so it will only be called when conditions are accepted
def gen1(self):
try:
MinNum = int(self.txt2.get())
MaxNum = int(self.txt3.get())
Num = int(self.txt4.get())
except ValueError:
messagebox.showerror(
"Error",
"Якщо не рвешся у висоту, шишок не наб'єш."
)
else:
Nums = " "
if MinNum <= MaxNum:
i = 0
while i < Num:
numOne = randint(MinNum, MaxNum)
Nums = Nums + ' ' + str(numOne)
i += 1
self.scrolltxt.config(state="normal") # enable the text box
self.scrolltxt.delete(1.0, END)
self.scrolltxt.insert(INSERT, str(Nums) + "\n")
self.scrolltxt.config(state="disabled") # disable the text box
self.clicked1() # call the 'clicked1' method
else:
messagebox.showerror(
"Error",
"Якщо не рвешся у висоту, шишок не наб'єш."
)

How could I use a number incrementor to show a specific amount of images in tkinter?

I am trying to connect dice png files in a window, but I can not seem to connect the number incrementor that goes up to 10(for 10 images) to align with the said amount of dice. Is there a way to connect them?
This is a define function(firstDicePage()). Asks for the amount of dice you want to roll.
# enables and disables the minus and plus button
def changeMinusState():
if (btn2['state'] == NORMAL):
btn2['state'] = DISABLED
else:
btn2['state'] = NORMAL
def changePlusState():
if (btn1['state'] == NORMAL):
btn1['state'] = DISABLED
else:
btn1['state'] = NORMAL
def increase():
counter.set(min(10, counter.get() + 1))
def decrease():
counter.set(max(0, counter.get() - 1))
lbl = Label(firstWindow, textvariable = counter, font='Helvetica 16 bold')
lbl.place(x=450, y=330)
btn1 = Button(firstWindow, text="+", font='Helvetica 16 bold', padx = 8, pady = 5, command = increase, fg="dark green", bg = "white")
btn1.place(x=499, y=320)
btn2 = Button(firstWindow, text ="-", font='Helvetica 16 bold', padx = 11.1, pady = 5, command = decrease, fg="dark green", bg = "white")
btn2.place(x=375, y=320)
btn4 = Button(firstWindow, text = "Next", font='Helvetica 16 bold', command=lambda: secondDicePage())
btn4.place(x = 800 , y = 530)
btn5 = Button(firstWindow, text = "Select", font ='Helvetica 16 bold', command = lambda: [changeMinusState(), changePlusState()], bg='#ffffff',
activebackground = 'green', padx = 19, pady = 2)
btn5.place(x = 400, y = 385)
This define function connects to the first one. It has the dice.
Updated
def secondDicePage(num_dices):
secondWindow = tkinter.Toplevel(window) # Create new window.
secondWindow.title("Dice Roller Generator")
# Change Icon photo
image = PhotoImage(file = "C:\\Users\\alexi\\Desktop\\Project Photos\\Dice logo.png")
secondWindow.iconphoto(False, image)
# Center
app_width = 900
app_height = 600
screen_width = secondWindow.winfo_screenwidth()
screen_height = secondWindow.winfo_screenheight()
x = (screen_width / 2) - (app_width / 2)
y= (screen_height / 2) - (app_height / 2)
secondWindow.geometry(f'{app_width}x{app_height}+{int(x)}+{int(y)}')
images
dice = ['dice_1.png', 'dice_2.png', 'dice_3.png', 'dice_4.png', 'dice_5.png', 'dice_6.png']
# middle image
img1 = ImageTk.PhotoImage(Image.open("C:\\Users\\alexi\\Desktop\\Project Photos\\questionmark.png"))
lbl1 = Label(secondWindow, image=img1)
lbl1.img = img1 # Save reference to image.
lbl1.pack()
lbl1.place(x = 380 , y = 95)
lbl2 = Label(secondWindow, image=img1)
lbl2.img = img1 # Save reference to image.
lbl2.pack()
lbl2.place(x = 195 , y = 95)
lbl3 = Label(secondWindow, image=img1)
lbl3.img = img1 # Save reference to image.
lbl3.pack()
lbl3.place(x = 565 , y = 95)
lbl4 = Label(secondWindow, image=img1)
lbl4.img = img1 # Save reference to image.
lbl4.pack()
lbl4.place(x = 746 , y = 95)
lbl5 = Label(secondWindow, image=img1)
lbl5.img = img1 # Save reference to image.
lbl5.pack()
lbl5.place(x = 1 , y = 95)
lbl6 = Label(secondWindow, image=img1)
lbl6.img = img1 # Save reference to image.
lbl6.pack()
lbl6.place(x = 380 , y = 300)
lbl7 = Label(secondWindow, image=img1)
lbl7.img = img1 # Save reference to image.
lbl7.pack()
lbl7.place(x = 195 , y =300)
lbl8 = Label(secondWindow, image=img1)
lbl8.img = img1 # Save reference to image.
lbl8.pack()
lbl8.place(x = 565 , y = 300)
lbl9 = Label(secondWindow, image=img1)
lbl9.img = img1 # Save reference to image.
lbl9.pack()
lbl9.place(x = 746 , y = 300)
lbl10 = Label(secondWindow, image=img1)
lbl10.img = img1 # Save reference to image.
lbl10.pack()
lbl10.place(x = 1 , y = 300)
Function for labels
def rolling_dice1():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl1.configure(image = image1, bg = '#B9C6C9')
lbl1.image = image1
def rolling_dice2():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl2.configure(image = image1, bg = '#B9C6C9')
lbl2.image = image1
def rolling_dice3():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl3.configure(image = image1, bg = '#B9C6C9')
lbl3.image = image1
def rolling_dice4():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl4.configure(image = image1, bg = '#B9C6C9')
lbl4.image = image1
def rolling_dice5():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl5.configure(image = image1, bg = '#B9C6C9')
lbl5.image = image1
def rolling_dice6():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl6.configure(image = image1, bg = '#B9C6C9')
lbl6.image = image1
def rolling_dice7():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl7.configure(image = image1, bg = '#B9C6C9')
lbl7.image = image1
def rolling_dice8():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl8.configure(image = image1, bg = '#B9C6C9')
lbl8.image = image1
def rolling_dice9():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl9.configure(image = image1, bg = '#B9C6C9')
lbl9.image = image1
def rolling_dice10():
image1 = ImageTk.PhotoImage(Image.open(random.choice(dice)))
lbl10.configure(image = image1, bg = '#B9C6C9')
lbl10.image = image1
widgets
btn1 = Button(secondWindow, text = "Back", font='Helvetica 16 bold', command = secondWindow.destroy)
btn1.place(x = 30 , y = 530)
btn2 = Button(secondWindow, text = "Roll Dice", font='Helvetica 16 bold', command = lambda: [rolling_dice1(), rolling_dice2(), rolling_dice3(), rolling_dice4(), rolling_dice5(), rolling_dice6(), rolling_dice7(), rolling_dice8(),
rolling_dice9(), rolling_dice10()])
btn2.place(x = 400 , y = 30)

trying to have the same label entry as the first frame to the second frame. Tkinter

trying to have the same label entry as the first frame to the second frame. have tried to add the second label to my function, however, it isn't registering as a label at all. trying to figure how the label entry can be saved. not sure if I should save it as a variable and then display it or just display the same label in both frames.
import tkinter as tk
import tkinter.messagebox as box
import csv
from tkinter import *
window = tk.Tk()
window.state('zoomed')
window.title('freshta otdering system')
def show_frame(fram):
fram.tkraise()
frame2 = tk.Frame(window)
frame3 = tk.Frame(window)
for frame in (frame1, frame2, frame3):
frame.grid(row=0,column=0,sticky='nsew')
filepath = '/Users/adamcleaver/Desktop/ICT/SAT part 1 /orders.csv'
File = open(filepath)
reader = csv.reader(File)
Data = list (reader)
del(Data[0])
list_of_entries = []
for x in list(range(0,len(Data))):
list_of_entries.append(Data[x][0])
var = StringVar(value = list_of_entries)
listbox1 = Listbox(frame2, listvariable = var)
listbox1.place(x= 10, y = 220, height = 500, width = 200)
def update():
index = listbox1.curselection()[0]
Foodlabel3.config(text = Data[index][1]) and Foodlabel2.config(text = Data[index][1])
Drinkslabel3.config(text = Data[index][2]) and Drinkslabel2.config(text = Data[index][2])
Pricelabel3.config(text = Data[index][3]) and Pricelabel2.config(text = Data[index][3])
return None
#using update function within the button
button1 = tk.Button(frame2, text="Update", command=update, fg = "blue", bg='yellow')
button1.place(x=400, y=450, height = 75, width = 125)
button2 = tk.Button(frame2, text="continue", command= lambda:show_frame(frame3), fg = "blue", bg='yellow')
button2.place(x=500, y=450, height = 75, width = 125)
Foodlabel = Label(frame2, text="Food", font=('Arial',20,'bold'),bg = '#F0EAD6').place(x= 295, y= 200)
Drinkslabel = Label(frame2, text="Drinks",font=('Arial',20,'bold'),bg = '#F0EAD6').place(x= 295, y= 300)
Pricelabel = Label(frame2, text="Total price ($)",font=('Arial',20,'bold'),bg = '#F0EAD6').place(x= 275, y=400)
Foodlabel2 = Label(frame2, text="",font=('Arial',20),bg = '#F0EAD6')
Foodlabel2.place(x= 425 , y= 200)
Drinkslabel2 = Label(frame2, text="",font=('Arial',20),bg = '#F0EAD6')
Drinkslabel2.place(x= 425, y= 300)
Pricelabel2 = Label(frame2, text="",font=('Arial',20),bg = '#F0EAD6' )
Pricelabel2.place(x=425, y= 400)
#label for login
tk.Label(frame2, text = 'Ordering' ,font=('Arial',36), fg = 'red', bg = '#F0EAD6' ).place(x=0, y=125)
tk.Label(frame2, text = 'Your order :' ,font=('Arial',36), bg = '#F0EAD6' ).place(x= 320, y=125)
#==================Frame 3 code ========================================
#label for login
tk.Label(frame2, text = 'Ordering' ,font=('Arial',36), fg = 'red', bg = '#F0EAD6' ).place(x=0, y=125)
Foodlabel3 = Label(frame3, text="",font=('Arial',20),bg = '#F0EAD6')
Foodlabel3.place(x= 425 , y= 200)
Drinkslabel3 = Label(frame3, text="",font=('Arial',20),bg = '#F0EAD6')
Drinkslabel3.place(x= 425, y= 300)
Pricelabel3 = Label(frame3, text="",font=('Arial',20),bg = '#F0EAD6' )
Pricelabel3.place(x=425, y= 400)
frame3_btn = tk.Button(frame3, text='Enter',command=lambda:show_frame(frame1))
frame3_btn.pack(fill='x',ipady=15)
show_frame(frame1)
window.mainloop()
That is not how you use and. You need:
def update():
index = listbox1.curselection()[0]
Foodlabel3.config(text = Data[index][1])
Foodlabel2.config(text = Data[index][1])
Drinkslabel3.config(text = Data[index][2])
Drinkslabel2.config(text = Data[index][2])
Pricelabel3.config(text = Data[index][3])
Pricelabel2.config(text = Data[index][3])

I'm creating a game in tkinter as a school project and it crashes without an error

I am a GCSE student in year 10 so I have only just started my course and proper coding. We were set a task to create a game called botmod where you control a character that collects people then returns them to a base. I created the game fine using general knowledge and getting help from Google for what I didn't understand. Once I finished the main program I started on creating a start menu where the user can set their own variables for the game such as grid size etc. once I had implemented this with the main program this is where the issue began.
Once I go through both menus and select all options the program stops responding then crashes.
I am aware this code is extremely messy and that I should not be using global variables or at least be avoiding them as much as possible but we haven't properly started OOP yet so I decided against diving into it.
Thank you in advance for the help.
from tkinter import *
from random import choice, shuffle
def Ending_Conditions():
global Player_Power, Players_Collected
if Players_Collected == 3:
Game_End("YOU WIN!")
elif Player_Power <= 0 and Players_Collected != 3:
Game_End("Game Over")
def Game_End(End_Option):
global Playing_Game, Game_Finished
if End_Option == "EXIT":
Playing_Game = False
Root.destroy()
else:
Game_Finished = True
Game_Canvas.create_rectangle(120, 120, 480, 300, fill = "#ffffff")
Game_Canvas.create_text(300, 210, text = End_Option, font = ('Abadi', 35, "bold"))
Continue_Button = Button(Root, text = 'Continue', command = lambda: Game_Restart('CONTINUE'))
Exit_Button = Button(Root, text = 'Exit', command = lambda: Game_Restart('EXIT'))
Continue_Button.pack()
Exit_Button.pack()
def Game_Restart(Restart_Option):
if Restart_Option == 'CONTINUE':
Root.destroy()
Restart_Game = True
if Restart_Option == 'EXIT':
Game_End('EXIT')
def Paused_UI():
global Game_Paused, Close_PausedUI
Close_PausedUI = Button(Root, text = 'Exit', command = Close_Paused_UI)
Close_PausedUI.pack()
Game_Paused = True
def Close_Paused_UI():
global Game_Paused, Close_PausedUI
Close_PausedUI.pack_forget()
Game_Paused = False
def Generate_Game():
global Game_Canvas, Game_Player, Game_Base, Player_Power, Power_Counter, People_Locations, Game_Paused, All_People, Game_Grid
Current_Colour = 0
Grid_Colour = []
Player_PosX, Player_PosY, Player_Storage, Players_Collected = 30, 30, 0, 0,
People_Locations = {0:[150, 450, 0], 1:[270, 330, 1], 2:[450, 90, 2]}
Game_Finished = False
# Generate UI
Game_Menu = Button(Root, text = 'Menu', command = Paused_UI)
Game_Menu.pack()
# Define grid colours
Grid_Colours = ['#009446', '#D4F0FF', '#5f6365']
# Generate power counter and pack canvas
Power_Counter = Label(Root, text = Player_Power)
Power_Counter.pack()
Game_Canvas.pack()
# Generate Grid and Colours
for y in range(Game_Grid):
for x in range(Game_Grid):
shuffle(Grid_Colours)
Game_Grid = Game_Canvas.create_rectangle(0+60*x, 0+60*y, 60+60*x, 60+60*y, fill = Grid_Colours[0])
Grid_Colour.append(Grid_Colours[0])
# Generate Robot Player
Game_Player = Game_Canvas.create_text(Player_PosX, Player_PosY, text = "R", font = ('Abadi', 35, "bold"))
# Generate Player Base
Game_Base = Game_Canvas.create_text(450, 330, text = "B", font = ('Abadi', 35, "bold"))
# Generate People
for i in range(Game_People):
Person_Location = People_Locations[0+i]
Game_Person = Game_Canvas.create_text(Person_Location[0], Person_Location[1], text = "P", font = ('Abadi', 35, "bold"), tag = 'Game_Person')
All_People = Game_Canvas.find_withtag('Game_Person')
All_People = list(All_People)
def Move_Player(event):
global Game_Canvas, Game_Player, Game_Base, Player_PosY, Player_PosX, Current_Colour, Player_Power, Power_Counter, Player_Storage, Players_Collected, Game_Finished, Current_Person
if event.char.lower() == '\x1b' and Game_Paused == False:
Paused_UI()
elif event.char.lower() == '\x1b' and Game_Paused == True:
Close_Paused_UI()
if Game_Paused == False and Game_Finished != True:
Movement_Value = Movement_Values[event.char.lower()]
if Player_PosX != Movement_Value[0] and Player_PosY != Movement_Value[1]:
# Detect current grid colour and configure power accordingly
Player_Power = Player_Power - Power_Values[Grid_Colour[Current_Colour]]
Power_Counter.configure(text = Player_Power)
Current_Colour = Current_Colour + Movement_Value[4]
# Delete the player then recreate in its new position
Game_Canvas.delete(Game_Player)
Player_PosX, Player_PosY = Player_PosX + Movement_Value[2], Player_PosY + Movement_Value[3]
Game_Player = Game_Canvas.create_text(Player_PosX, Player_PosY, text = "R", font = ('Abadi', 35, "bold"))
# Detect Person
for item in People_Locations:
Person_Location = People_Locations[item]
if Player_PosX == Person_Location[0] and Player_PosY == Person_Location[1] and Player_Storage != 1:
Current_Person = Person_Location[2]
Game_Canvas.delete(All_People[Current_Person])
Player_Storage += 1
if Player_PosX == 450 and Player_PosY == 330:
if Player_Storage == 1:
Player_Storage -= 1
Players_Collected += 1
Clear_Current = People_Locations[Current_Person]
Clear_Current = Clear_Current[2]
People_Locations.pop(Clear_Current)
Ending_Conditions()
def Start_Game():
global Start_Canvas
Start_Canvas = Canvas(Root, width = 600, height = 500, bd=0, highlightthickness=0, bg = '#ffffff')
Start_Canvas.pack()
Title = Start_Canvas.create_text(300, 163, text = "BOTMOD", font = ('Cinema Gothic BTN Shadow', 75, 'normal'))
Play_Button = Button(text = "PLAY", width = 10, font=('Arial', 15), command = Play_Game)
Play_Button = Start_Canvas.create_window(300, 325, window = Play_Button)
Exit_Button = Button(text = "EXIT", width = 10, font=('Arial', 15), command = lambda: Game_End("EXIT"))
Exit_Button = Start_Canvas.create_window(300, 375, window = Exit_Button)
def Play_Game():
global Menu_Canvas, Grid_Entry, Power_Entry, People_Entry
Start_Canvas.destroy()
Menu_Canvas = Canvas(Root, width = 600, height = 500, bd=0, highlightthickness=0, bg = '#C0C0C0')
Menu_Canvas.pack()
Title_Rectangle = Menu_Canvas.create_rectangle(120, 10, 480, 100, fill = '#000000')
Slider_Rectangle = Menu_Canvas.create_rectangle(120, 110, 480, 430, fill = '#000000')
Footer_Rectangle = Menu_Canvas.create_rectangle(120, 440, 480, 490, fill = '#000000')
Title = Menu_Canvas.create_text(300, 55, text = "BOTMOD", font = ('Cinema Gothic BTN Shadow', 55, 'normal'), fill = '#ffffff')
Description_Text = Label(text = "Set Game Options", font=('Arial', 15, 'bold'), bg = '#000000', fg = '#ffffff')
Description_Text = Menu_Canvas.create_window(300, 145, window = Description_Text)
Power_Text = Label(text = "Robot Power", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
Power_Text = Menu_Canvas.create_window(300, 195, window = Power_Text)
Power_Entry = Scale(from_= 50, to = 350, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
Power_Entry = Menu_Canvas.create_window(300, 225, window = Power_Entry)
People_Text = Label(text = "Person Count", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
People_Text = Menu_Canvas.create_window(300, 280, window = People_Text)
People_Entry = Scale(from_= 3, to = 10, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0, state=DISABLED)
People_Entry = Menu_Canvas.create_window(300, 310, window = People_Entry)
Grid_Text = Label(text = "Grid Count", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
Grid_Text = Menu_Canvas.create_window(300, 365, window = Grid_Text)
Grid_Entry = Scale(from_= 5, to = 15, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
Grid_Entry = Menu_Canvas.create_window(300, 395, window = Grid_Entry)
Play_Button = Button(text = "OK", width = 15, font=('Cinema Gothic BTN Shadow', 10), command = lambda: Init_Game("DEFAULT"), bg = '#000000', fg = '#ffffff')
Play_Button = Menu_Canvas.create_window(400, 465, window = Play_Button)
PlayWD_Button = Button(text = "Use Defaults", width = 15, font=('Cinema Gothic BTN Shadow', 10), command = lambda: Init_Game("CUSTOM"), bg = '#000000', fg = '#ffffff')
PlayWD_Button = Menu_Canvas.create_window(200, 465, window = PlayWD_Button)
def Init_Game(Game_Options):
global Grid_Count, Player_PosY, Player_PosX, Game_Paused, Game_Finished, Playing_Game, Player_Power, Game_Grid, Player_Movement, Game_People, Game_Canvas, Menu_Canvas, Grid_Entry, Power_Entry, People_Entry, Grid_Rectangle
if Game_Options == "DEFAULT":
Game_Grid = 10
Grid_Rectangle = 600/10
Player_Movement = Grid_Rectangle/2
Player_Power = 150
Game_People = 3
else:
Game_Grid = Grid_Entry.get()
Grid_Rectangle = 600/Game_Grid
Player_Movement = Grid_Rectangle/2
Player_Power = Power_Entry.get()
Game_People = People_Entry.get()
Menu_Canvas.destroy()
Playing_Game = True
Game_Paused = False
Restart_Game = False
Movement_Values = {'w':(1000, 30, 0, -60, -10), 'a':(30, 1000, -60, 0, -1), 's':(1000, 570, 0, 60, 10), 'd':(570, 1000, 60, 0, 1)}
Power_Values = {'#009446':2, '#D4F0FF':1, '#5f6365':3}
People_Locations = {0:[150, 450, 0], 1:[270, 330, 1], 2:[450, 90, 2]}
while Playing_Game == True:
Restart_Game = False
while Restart_Game == False:
if Playing_Game == False:
break
else:
Root = Tk()
Game_Canvas = Canvas(Root, width = 600, height = 600, bd=0, highlightthickness=0)
Generate_Game()
Root.bind('<KeyPress>', Move_Player)
Root.protocol("WM_DELETE_WINDOW", lambda: Game_End("EXIT"))
if Playing_Game == False:
break
Root = Tk()
Start_Game()
Root.mainloop()
Had a look today and it turns out the loops at the bottom were what caused the issue not 100% sure what I did as it was trial and error but I will post the code anyway.
Also that code isn't finished completely yet.
from tkinter import *
from random import choice, shuffle
def Ending_Conditions():
global Player_Power, Players_Collected
if Players_Collected == 3:
Game_End("YOU WIN!")
elif Player_Power <= 0 and Players_Collected != 3:
Game_End("Game Over")
def Game_End(End_Option):
global Playing_Game, Game_Finished
if End_Option == "EXIT":
Playing_Game = False
Root.destroy()
else:
Game_Finished = True
Game_Canvas.create_rectangle(120, 120, 480, 300, fill = "#ffffff")
Game_Canvas.create_text(300, 210, text = End_Option, font = ('Abadi', 35, "bold"))
Continue_Button = Button(Root, text = 'Continue', command = Game_Restart)
Exit_Button = Button(Root, text = 'Exit', command = lambda: Game_End('EXIT'))
Continue_Button.pack()
Exit_Button.pack()
def Game_Restart():
global Already_Played
Root.destroy()
Restart_Game = True
Already_Played = True
def Paused_UI():
global Game_Paused, Close_PausedUI
Close_PausedUI = Button(Root, text = 'Exit', command = Close_Paused_UI)
Close_PausedUI.pack()
Game_Paused = True
def Close_Paused_UI():
global Game_Paused, Close_PausedUI
Close_PausedUI.pack_forget()
Game_Paused = False
def Generate_Game():
global Game_Canvas, Game_Player, Game_Base, Player_Power, Power_Counter, People_Locations, Game_Paused, All_People, Game_Gridcount, Current_Colour, Player_PosY, Player_PosX, Grid_Colour, Players_Collected, Player_Storage
Current_Colour = 0
Grid_Colour = []
Player_PosX, Player_PosY, Player_Storage, Players_Collected, Players_Removed = 300/Game_Gridcount, 300/Game_Gridcount, 0, 0, 0
People_Locations = {0:[150, 450, 0], 1:[270, 330, 1], 2:[450, 90, 2]}
Game_Finished = False
# Generate UI
Game_Menu = Button(Root, text = 'Menu', command = Paused_UI)
Game_Menu.pack()
# Define grid colours
Grid_Colours = ['#009446', '#D4F0FF', '#5f6365']
# Generate power counter and pack canvas
Power_Counter = Label(Root, text = Player_Power)
Power_Counter.pack()
Game_Canvas.pack()
# Generate Grid and Colours
for y in range(Game_Gridcount):
for x in range(Game_Gridcount):
shuffle(Grid_Colours)
Game_Grid = Game_Canvas.create_rectangle(Grid_Rectangle*x, Grid_Rectangle*y, Grid_Rectangle+Grid_Rectangle*x, Grid_Rectangle+Grid_Rectangle*y, fill = Grid_Colours[0])
Grid_Colour.append(Grid_Colours[0])
# Generate Robot Player
Game_Player = Game_Canvas.create_text(Player_PosX, Player_PosY, text = "R", font = ('Abadi', 450//Game_Gridcount, "bold"))
# Generate Player Base
Game_BaseX, Game_BaseY = Grid_Rectangle*(Game_Gridcount-1.5), Grid_Rectangle*(Game_Gridcount-2.5)
Game_Base = Game_Canvas.create_text(Game_BaseX, Game_BaseY, text = "B", font = ('Abadi', 450//Game_Gridcount, "bold"))
# Generate People
for i in range(Game_People):
Person_Location = People_Locations[i] Grid_Rectangle*(Game_Gridcount-1.5)
Game_Person = Game_Canvas.create_text(Grid_Rectangle*(Game_Gridcount-Person_Location[0]), (Grid_Rectangle*(Game_Gridcount-Person_Location[1]), text = "P", font = ('Abadi', 450//Game_Gridcount, "bold"), tag = 'Game_Person')
All_People = Game_Canvas.find_withtag('Game_Person')
All_People = list(All_People)
def Move_Player(event):
global Game_Canvas, Game_Player, Game_Base, Player_PosY, Player_PosX, Current_Colour, Player_Power, Power_Counter, Player_Storage, Players_Collected, Game_Finished, Current_Person
if event.char.lower() == '\x1b' and Game_Paused == False:
Paused_UI()
elif event.char.lower() == '\x1b' and Game_Paused == True:
Close_Paused_UI()
if Game_Paused == False and Game_Finished != True:
Movement_Value = Movement_Values[event.char.lower()]
if Player_PosX != Movement_Value[0] and Player_PosY != Movement_Value[1]:
# Detect current grid colour and configure power accordingly
Player_Power = Player_Power - Power_Values[Grid_Colour[Current_Colour]]
Power_Counter.configure(text = Player_Power)
Current_Colour = Current_Colour + Movement_Value[4]
# Delete the player then recreate in its new position
Game_Canvas.delete(Game_Player)
Player_PosX, Player_PosY = Player_PosX + Movement_Value[2], Player_PosY + Movement_Value[3]
Game_Player = Game_Canvas.create_text(Player_PosX, Player_PosY, text = "R", font = ('Abadi', 450//Game_Gridcount, "bold"))
# Detect Person
for item in People_Locations:
Person_Location = People_Locations[item]
if Player_PosX == Person_Location[0] and Player_PosY == Person_Location[1] and Player_Storage != 1:
Current_Person = Person_Location[2]
Game_Canvas.delete(All_People[Current_Person])
Player_Storage += 1
if Player_PosX == 450 and Player_PosY == 330:
if Player_Storage == 1:
Player_Storage -= 1
Players_Collected += 1
Clear_Current = People_Locations[Current_Person]
Clear_Current = Clear_Current[2]
People_Locations.pop(Clear_Current)
Ending_Conditions()
def Start_Game():
global Start_Canvas
Start_Canvas = Canvas(Root, width = 600, height = 500, bd=0, highlightthickness=0, bg = '#ffffff')
Start_Canvas.pack()
Title = Start_Canvas.create_text(300, 163, text = "BOTMOD", font = ('Cinema Gothic BTN Shadow', 75, 'normal'))
Play_Button = Button(text = "PLAY", width = 10, font=('Arial', 15), command = Play_Game)
Play_Button = Start_Canvas.create_window(300, 325, window = Play_Button)
Exit_Button = Button(text = "EXIT", width = 10, font=('Arial', 15), command = lambda: Game_End("EXIT"))
Exit_Button = Start_Canvas.create_window(300, 375, window = Exit_Button)
def Play_Game():
global Menu_Canvas, Grid_Entry, Power_Entry, People_Entry
if Already_Played == False:
Start_Canvas.destroy()
Menu_Canvas = Canvas(Root, width = 600, height = 500, bd=0, highlightthickness=0, bg = '#C0C0C0')
Menu_Canvas.pack()
Title_Rectangle = Menu_Canvas.create_rectangle(120, 10, 480, 100, fill = '#000000')
Slider_Rectangle = Menu_Canvas.create_rectangle(120, 110, 480, 430, fill = '#000000')
Footer_Rectangle = Menu_Canvas.create_rectangle(120, 440, 480, 490, fill = '#000000')
Title = Menu_Canvas.create_text(300, 55, text = "BOTMOD", font = ('Cinema Gothic BTN Shadow', 55, 'normal'), fill = '#ffffff')
Description_Text = Label(text = "Set Game Options", font=('Arial', 15, 'bold'), bg = '#000000', fg = '#ffffff')
Description_Text = Menu_Canvas.create_window(300, 145, window = Description_Text)
Power_Text = Label(text = "Robot Power", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
Power_Text = Menu_Canvas.create_window(300, 195, window = Power_Text)
Power_Entry = Scale(Root, from_= 50, to = 350, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
Power_Entrys = Menu_Canvas.create_window(300, 225, window = Power_Entry)
People_Text = Label(text = "Person Count", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
People_Text = Menu_Canvas.create_window(300, 280, window = People_Text)
People_Entry = Scale(Root, from_= 2, to = 10, orient = HORIZONTAL, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
People_Entrys = Menu_Canvas.create_window(300, 310, window = People_Entry)
Grid_Text = Label(text = "Grid Count", font=('Cinema Gothic BTN Shadow', 15), bg = '#000000', fg = '#ffffff')
Grid_Text = Menu_Canvas.create_window(300, 365, window = Grid_Text)
Grid_Entry = Scale(Root, from_= 6, to = 14, orient = HORIZONTAL, resolution = 2, bg = '#000000', fg = '#ffffff', highlightthickness=0, bd = 0)
Grid_Entrys = Menu_Canvas.create_window(300, 395, window = Grid_Entry)
Play_Button = Button(text = "OK", width = 15, font=('Cinema Gothic BTN Shadow', 10), command = lambda: Init_Game("CUSTOM"), bg = '#000000', fg = '#ffffff')
Play_Button = Menu_Canvas.create_window(400, 465, window = Play_Button)
PlayWD_Button = Button(text = "Use Defaults", width = 15, font=('Cinema Gothic BTN Shadow', 10), command = lambda: Init_Game("DEFAULT"), bg = '#000000', fg = '#ffffff')
PlayWD_Button = Menu_Canvas.create_window(200, 465, window = PlayWD_Button)
def Init_Game(Game_Options):
global Player_PosY, Player_PosX, Game_Paused, Game_Finished, Playing_Game, Player_Power, Game_Gridcount, Player_Movement, Game_People, Game_Canvas, Movement_Values, Power_Values, Grid_Rectangle
if Game_Options == "DEFAULT":
Game_Gridcount = 10
Grid_Rectangle = 600/10
Player_Movement = Grid_Rectangle/2
Player_Power = 150
Game_People = 3
elif Game_Options == "CUSTOM":
Game_Gridcount = Grid_Entry.get()
Grid_Rectangle = 600/Game_Gridcount
Player_Movement = Grid_Rectangle/2
Player_Power = Power_Entry.get()
Game_People = People_Entry.get()
Movement_Values = {'w':(1000, 300/Game_Gridcount, 0, -600/Game_Gridcount, 10), 'a':(300/Game_Gridcount, 1000, -600/Game_Gridcount, 0, -1), 's':(1000, 600-Player_Movement, 0, 600/Game_Gridcount, Game_Gridcount-Game_Gridcount*2), 'd':(600-Player_Movement, 1000, 600/Game_Gridcount, 0, 1)}
Power_Values = {'#009446':2, '#D4F0FF':1, '#5f6365':3}
People_Locations = {0:[1.5, 1.5, 0], 1:[1.5, 4.5, 1], 2:[1.5, 1.5, 2], 3:[1.5, 1.5, 3], 4:[1.5, 1.5, 4], 5:[1.5, 1.5, 5], 6:[1.5, 1.5, 6], 7:[1.5, 1.5, 7], 8:[1.5, 1.5, 8], 9:[1.5, 1.5, 9], 10:[1.5, 1.5, 10]}
Menu_Canvas.destroy()
Game_Canvas = Canvas(Root, width = 600, height = 600, bd=0, highlightthickness=0)
Generate_Game()
Root.bind('<KeyPress>', Move_Player)
Root.protocol("WM_DELETE_WINDOW", lambda: Game_End("EXIT"))
Playing_Game = True
Game_Paused = False
Restart_Game = False
Already_Played = False
while True:
while Restart_Game == False:
if Playing_Game == False:
break
else:
Game_Finished = False
Grid_Colour = []
Power_Values = {'#009446':2, '#D4F0FF':1, '#5f6365':3}
Root = Tk()
if Already_Played == True:
Play_Game()
Root.mainloop()
elif Already_Played == False:
Start_Game()
Root.mainloop()
break

Creating Tkinter Text boxes and inserting into a dictionary

I have a long chunk of code. I do not want to paste it all here, so let me explain what I am trying to accomplish here. Based on a number provided by the user I want to create that many text boxes and then get what is entered into that text box and insert that into the dictionary. I have tried this a few ways and just cannot get it to work correctly. The list is either empty or it only contains the last text box as the value for each key.
def multiple_choice():
def add():
top.destroy()
top = Tk()
top.title("Add Question")
w = 800
h = 800
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
question = Label(top, text="Question to be asked?", font = "Times 14 bold", fg = "blue")
question.grid(row = 2, column = 4)
questionText = Text(top, borderwidth = 5, width=50,height=5, wrap=WORD, background = 'grey')
questionText.grid(row = 3, column = 4)
numQuestions = Label(top, text = "Number of answer choices?", font = "Times 14 bold", fg = "blue")
numQuestions.grid(row = 4, column=4)
num = Entry(top, bd = 5)
num.grid(row=5, column = 4)
answerList = {}
def multiple():
def preview():
preview = Tk()
top.title("Question Preview")
w = 500
h = 500
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
top.geometry('%dx%d+%d+%d' % (w, h, x, y))
title = Label(preview, text = "Short Answer Question Preview", font = "Times 18 bold", fg = "blue" )
title.grid(row = 0, column = 2)
qtext = "Question text will read: "
ques = Label(preview, text = qtext)
ques.grid(row=1, column = 2)
ques2 = Label( preview, text = questionText.get("1.0",END))
let = 'A'
i = 1
for word in answerList:
prev = let + ": " + word
ans = Label(preview, text = prev)
ans.grid(row=1+i, column = 2)
let = chr(ord(let) + 1)
answerCor = "The correct answer(s): "
a = Label(preview, text = answerCor)
a.grid(row=4, column = 2)
b = Label(preview, text = cor.get)
b.grid(row=5, column = 2)
if num.get().isdigit():
number = int(num.get())
AnswerChoices = Label(top, text = "Answer Choices?", font = "Times 14 bold", fg = "blue")
AnswerChoices.grid(row = 6, column=4)
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
print answerList
correct = Label(top, text = "Correct Answer(s) (seperated by commas)",
font = "Times 14 bold", fg = "blue")
correct.grid(row =99 , column=4)
cor = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
cor.grid(row=100, column = 4)
else:
error = Tk()
w = 500
h = 100
ws = top.winfo_screenwidth()
hs = top.winfo_screenheight()
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
error.geometry('%dx%d+%d+%d' % (w, h, x, y))
text = "ERROR: You must enter an integer number"
Label(error,text = text, fg = "red", font = "Times 16 bold").pack()
MyButton5 = Button(top, text="Preview Question", width=20, command = preview, anchor=S)
MyButton5.grid(row=102, column=5)
MyButton4 = Button(top, text="Finish and Add Question", width=20, command = add, anchor=S)
MyButton4.grid(row=102, column=2)
but = Button(top, text="Submit", width=10, command = multiple)
but.grid(row=6, column = 4)
top.mainloop()
def button():
MyButton21 = Button(quiz, text="Short Answer Question", width=20, command = short_answer)
MyButton21.grid(row=8, column=2)
MyButton22 = Button(quiz, text="True/False Question", width=20, command = true_false)
MyButton22.grid(row=8, column=4)
MyButton23 = Button(quiz, text="Multiple Choice Question", width=20, command = multiple_choice)
MyButton23.grid(row=9, column=2)
#MyButton24 = Button(quiz, text="Matching Question", width=20, command = matching)
#MyButton24.grid(row=9, column=4)
MyButton25 = Button(quiz, text="Ordering Question", width=20, command =order)
MyButton25.grid(row=10, column=2)
MyButton26 = Button(quiz, text="Fill in the Blank Question", width=20, command = fill_blank)
MyButton26.grid(row=10, column=4)
MyButton3 = Button(quiz, text="Finsh Quiz", width=10, command = quiz)
MyButton3.grid(row=12, column=3)
quiz = Tk()
w = 700
h = 300
ws = quiz.winfo_screenwidth()
hs = quiz.winfo_screenheight()
x = 0
y = 0
quiz.geometry('%dx%d+%d+%d' % (w, h, x, y))
quiz.title("eCampus Quiz Developer")
L1 = Label(quiz, text="Quiz Title?")
L1.grid(row=0, column=0)
E1 = Entry(quiz, bd = 5)
E1.grid(row=0, column=3)
name_file = E1.get()
name_file = name_file.replace(" ", "")
name_file = name_file + ".txt"
with open(name_file,"w") as data:
MyButton1 = Button(quiz, text="Submit", width=10, command = button)
MyButton1.grid(row=1, column=3)
quiz.mainloop()
I am trying to create the dictionary using this chunk of code:
i = 0
let = 'A'
while i < number:
letter = Label(top, text = let)
letter.grid(row = 8+(i*4), column = 3)
answer = Text(top, borderwidth = 5, width=50, height=3, wrap=WORD, background = 'grey')
answer.grid(row = 8+(i*4), column = 4)
answerList[let] = answer.get("1.0",END)
i = i+1
let = chr(ord(let) + 1)
I have even tried putting a loop in the preview function but that is when the last box was the only value contained in the dictionary. Any ideas would be appreciated
Please see my commeneted snippet below which demonstrates this:
from tkinter import *
class App:
def __init__(self, root):
self.root = root
self.entry = Entry(self.root) #entry to input number of entries later
self.button = Button(self.root, text="ok", command=self.command) #calls command to draw the entry boxes
self.frame = Frame(self.root)
self.entry.pack()
self.button.pack()
self.frame.pack()
def command(self):
self.frame.destroy() #destroys frame and contents
self.frame = Frame(self.root) #recreates frame
self.text = [] #empty array to store entry boxes
for i in range(int(self.entry.get())):
self.text.append(Entry(self.frame, text="Question "+str(i))) #creates entry boxes
self.text[i].pack()
self.done = Button(self.frame, text="Done", command=self.dict) #button to call dictionary entry and print
self.done.pack()
self.frame.pack()
def dict(self):
self.dict = {}
for i in range(len(self.text)):
self.dict.update({self.text[i].cget("text"): self.text[i].get()})
#the above line adds a new dict entry with the text value of the respective entry as the key and the value of the entry as the value
print(self.dict) #prints the dict
root = Tk()
App(root)
root.mainloop()
The above asks the user how many entry widgets they want to create, fills a frame with those entry widgets and then iterates through the list which contains them on the press of a button, adding a new dictionary entry for each entry widget, where the key of the dict is the attribute text for each entry and the value of the dict is the value of each entry.

Categories