How do I create a 'next' button in Tkinter - python

I have to make a Photo Browser GUI, and I need to be able to browse through the photos, how would I Go about making a 'next' button and a 'previous'. I am a complete beginner so any help is appreciated

As simple as it can be:
1 - Create a master window, usually name root:
root = Tk()
2 - Add a Main Frame for Displaying your Picture (current photo):
framePhoto = Frame(root, bg='gray50',relief = RAISED, width=800, height=600, bd=4)
3 - Add two buttons, Next & Prev:
prevBtn = Button(self.framePhoto, text='Previous', command=lambda s=self: s.getImgOpen('prev'),
bg='blue', fg='red').place(relx=0.85, rely=0.99, anchor=SE)
nextBtn = Button(self.framePhoto, text='Next', command=lambda s=self: s.getImgOpen('next'),
bg='green', fg='black').place(relx=0.90, rely=0.99, anchor=SE)
4 - You need to add method to handle listing all pictures in your current directory or directory that you input to the application, example:
def getImgList(self, path, ext):
imgList = [os.path.normcase(f) for f in os.listdir(path)]
imgList = [os.path.join(path, f) for f in imgList if os.path.splitext(f)[1] == ext]
self.images.extend(imgList)
5 - Another method to open and display the image:
def getImgOpen(self,seq):
print 'Opening %s' % seq
if seq=='ZERO':
self.imgIndex = 0
elif (seq == 'prev'):
if (self.imgIndex == 0):
self.imgIndex = len(self.images)-1
else:
self.imgIndex -= 1
elif(seq == 'next'):
if(self.imgIndex == len(self.images)-1):
self.imgIndex = 0
else:
self.imgIndex += 1
self.masterImg = Image.open(self.images[self.imgIndex])
self.master.title(self.images[self.imgIndex])
self.masterImg.thumbnail((400,400))
self.img = ImageTk.PhotoImage(self.masterImg)
self.lbl['image'] = self.img
return
This is as simple as I can explain to you and the above mentioned piece of codes are for clarification.

Here is the complete code, as explained by Iron Fist answer. I assembled it, so I it might be useful.
from Tkinter import *
import os
from PIL import ImageTk,Image
class Display(object):
def __init__(self):
self.images = [];
self.imgIndex = 0;
self.master= Tk()
self.framePhoto = Frame(self.master, bg='gray50',relief = RAISED, width=800, height=600, bd=4)
self.framePhoto.pack();
prevBtn = Button(self.framePhoto, text='Previous', command=lambda s=self: s.getImgOpen('prev')).place(relx=0.85, rely=0.99, anchor=SE)
nextBtn = Button(self.framePhoto, text='Next', command=lambda s=self: s.getImgOpen('next')).place(relx=0.90, rely=0.99, anchor=SE)
#prevBtn.pack();
#nextBtn.pack();
self.getImgList('test_2/test_2','.bmp')
mainloop()
def getImgList(self, path, ext):
imgList = [os.path.normcase(f) for f in os.listdir(path)]
imgList = [os.path.join(path, f) for f in imgList if os.path.splitext(f)[1] == ext]
self.images.extend(imgList)
#print self.images
def getImgOpen(self,seq):
print 'Opening %s' % seq
if seq=='ZERO':
self.imgIndex = 0
elif (seq == 'prev'):
if (self.imgIndex == 0):
self.imgIndex = len(self.images)-1
else:
self.imgIndex -= 1
elif(seq == 'next'):
if(self.imgIndex == len(self.images)-1):
self.imgIndex = 0
else:
self.imgIndex += 1
self.masterImg = Image.open(self.images[self.imgIndex])
self.master.title(self.images[self.imgIndex])
self.masterImg.thumbnail((400,400))
self.img = ImageTk.PhotoImage(self.masterImg)
label = Label(image=self.img)
label.image = self.img # keep a reference!
label.pack()
label.place(x=100,y=100)
#self.lbl['image'] = self.img
return
d = Display();
d.getImgOpen('next')

Related

is there a way to grid an extra button while running your program in tkinter correctly?

I'm making an mp3 player app and I want the user to be able to add playlists (which will be buttons in a grid system.
Like so.
However in this state when I'm trying to add a playlist button this happens:
The top buttons and the button i just added get squeezed off and the scrollbar is stuck (I can't use it)
I've tried refreshing by self.playlist_frame.update_idletasks() after running create_playlists() but it doesn't seem to change anything
this is my code so you can test it:
import os
import tkinter as tk
from tkinter import ttk
from PIL import Image, ImageTk
class MyApp:
def __init__(self):
self.root = tk.Tk()
self.width = self.root.winfo_screenwidth()
self.height = self.root.winfo_screenheight()
self.height = self.root.winfo_screenheight() - int(self.height / 13)
self.root.geometry(f'{self.width}x{self.height}')
self.root.title("Mp3")
self.c = '#14141D'
self.playlists_buttons_list = []
self.playlists = {}
self.helping_d = {}
self.main = ttk.Notebook(self.root)
self.playlists_tab = tk.Frame(self.main)
self.playlist_menu_frame = tk.Frame(self.playlists_tab, bg=self.c)
self.playlists_canvas = tk.Canvas(self.playlists_tab, bg=self.c)
self.playlist_frame = tk.Frame(self.playlists_canvas, bg=self.c)
self.playlists_scrollbar = ttk.Scrollbar(self.playlists_tab, orient='vertical',
command=self.playlists_canvas.yview)
self.add_playlist_win = tk.Toplevel(self.root)
self.add_playlists_button = tk.Button(self.playlist_frame)
self.default_img = Image.open('images/default.png').resize((75, 72))
self.default_img = ImageTk.PhotoImage(self.default_img)
self.add_img = Image.open('images/add.png').resize((50, 50))
self.add_img = ImageTk.PhotoImage(self.add_img)
self.widgets()
self.root.mainloop()
def widgets(self):
self.playlists_tab.place(height=self.height, width=self.width, x=0, y=0)
self.main.add(self.playlists_tab, text="Playlists")
self.main.pack(expand=1, fill="both")
self.playlist_frame = tk.Frame(self.playlists_canvas, bg=self.c)
self.playlists_canvas.create_window((0, 0), window=self.playlist_frame, anchor='center')
self.playlists_canvas.config(bg=self.c)
self.playlists_canvas.place(height=int(self.height / 1.428), width=self.width, x=0, y=int(self.height / 9))
self.add_playlists_button = tk.Button(self.playlists_canvas, image=self.add_img, bg=self.c, bd=0,
command=self.add_playlists)
self.add_playlists_button.place(x=1284, y=75)
self.playlists_scrollbar.pack(side='right', fill='y')
self.playlists_canvas.config(yscrollcommand=self.playlists_scrollbar.set)
self.playlists_canvas.bind('<Configure>', lambda e: self.playlists_canvas.configure(
scrollregion=self.playlists_canvas.bbox('all')))
if os.path.getsize('playlistsnames.txt') != 0:
lines = open('playlistsnames.txt', 'r', encoding='utf-8').read().splitlines()
for i in lines:
self.playlists[i] = []
self.create_playlists()
def create_playlists(self):
self.playlists_buttons_list = []
for i in range(len(self.playlists.keys())):
self.playlists_buttons_list.append(tk.Button(self.playlist_frame, bg=self.c,
text=' ' + list(self.playlists.keys())[i].split('!')[0],
fg='white', image=self.default_img, height=280, width=300))
row = 0
column = 0
for i in self.playlists_buttons_list:
if column > 3:
row += 1
column = 0
if column > 7:
row += 1
column = 0
i.grid(row=row, column=column)
column += 1
def get_name(self):
self.name_of_plst = self.plst_entry.get()
self.playlists[self.name_of_plst] = []
self.create_playlists()
with open('playlistsnames.txt', 'a', encoding='utf-8') as names_file:
names_file.write(self.name_of_plst + '!\n')
def add_playlists(self):
self.add_playlist_win = tk.Toplevel(self.root)
self.name_label = tk.Label(self.add_playlist_win, text='Name:', bg=self.c, fg='pink').pack()
self.plst_entry = tk.Entry(self.add_playlist_win)
self.plst_entry.pack()
self.confirm_btn = tk.Button(self.add_playlist_win, text='Confirm', bg=self.c, fg='pink',
command=self.get_name).pack()
self.add_playlist_win.mainloop()
MyApp()
I should also mention that because I store the playlist names in a file called playlistnames.txt when I rerun the program I can see all the playlist buttons plus the one I created before and things work just fine.
So what I want is making the grid update and work while running the app without having to rerun the app of course
My playlistsnames.txt file has this format:
rock!
metal!
chill!
rap!
jazz!
blues!
hard rock!
trap!
Any suggestions would be helpful!
Thanks in advance!

Pause function in pygame mixer is not working

I am currently making a GUI with Tkinter that plays music. The program is able to correctly play the songs, and I am trying to implement a pause button. This is the code I have, does anyone know why this might not be working? I know the button is linked properly since I have tried printing something out when the button is clicked, and that works. Also, there are no error messages, the audio is just not pausing.
import pygame
from tkinter import *
import os
import urllib.request
import urllib.parse
import re
import requests
from PIL import ImageTk, Image
class Application(Frame):
def __init__(self, master):
super().__init__(master)
self.grid()
pygame.mixer.init()
self.downloadNum = 1
self.pack(fill = BOTH, expand = 1)
self.songDict = {}
num = 1
while True:
if os.path.exists(str(num)+'.jpg'):
os.remove(str(num)+'.jpg')
num += 1
else:
break
self.create_widgets()
def create_widgets(self):
Label(self, text="Available Songs").grid(row=0, column=0)
for filename in os.listdir(r'C:\Users\alvin\Documents\School'):
if filename.endswith(".mp3"):
string = ""
for x in filename:
if x == "_":
string += " "
else:
if x == ".":
break
string += x
Label(self, text=string).grid()
Label(self, text = "Enter your song!").grid(row=0, column = 1)
self.entryBox = Entry(self)
self.entryBox.grid(row=1, column =1)
Button(self, text="Play!", command = self.playSong).grid(row=2, column =1)
Label(self).grid(row=3, column =1)
Label(self, text="Currently Playing:").grid(row=4, column=1)
self.playing = Label(self, text="")
self.playing.grid(row=5, column=1)
def playSong(self):
self.song = self.entryBox.get()
self.newsong = ""
for x in self.song:
if x == " ":
self.newsong += "_"
else:
self.newsong += x
self.newsong = self.newsong.title()
self.newsong = self.newsong + ".mp3"
pygame.mixer.music.load(self.newsong)
pygame.mixer.music.play(0)
self.playing.configure(text=self.song.title())
query_string = urllib.parse.urlencode({"search_query": self.song.title()})
html_content = urllib.request.urlopen("http://www.youtube.com/results?" + query_string)
search_results = re.findall(r'href=\"\/watch\?v=(.{11})', html_content.read().decode())
f = open(str(self.downloadNum) +'.jpg','wb')
f.write(requests.get('https://img.youtube.com/vi/' + search_results[0] + '/default.jpg').content)
f.close()
self.songDict[self.downloadNum] = self.newsong
load = Image.open(str(self.downloadNum) + ".jpg")
render = ImageTk.PhotoImage(load)
img = Label(self, image=render)
img.image = render
img.place(x=145, y=135)
self.downloadNum += 1
Label(self).grid(row=6, column =0)
Label(self).grid(row=7, column=0)
Label(self).grid(row=8, column=0)
Label(self).grid(row=9, column=0)
Label(self).grid(row=10, column=0)
pauseButton = Button(self, text="||", command = self.pause)
pauseButton.grid(row = 11, column = 1)
def pause(self):
pygame.mixer.pause()
root = Tk()
root.title("MP3 Player")
root.geometry("400x400")
app = Application(root)
root.mainloop()
try using:
pygame.mixer.music.pause()
instead of:
pygame.mixer.pause()

Tkinter click event does not trigger; keyboard does

I found this neat code here that uses Tkinter to display a series of images. I extended the code to use the 'z' and 'x' keys to browse through the images and 'q' to quit. Also, I would like to be able to click on the individual frames and obtain the image coordinates of where I clicked. While the keyboard interaction works just fine, the mouse click event does not get triggered. I wonder why that is, since the key strokes are triggered just fine.
This is the code I have:
#!/usr/bin/env python
from Tkinter import *
import Image, ImageTk
import os, sys
class Clicker:
def __init__(self, master, filelist):
self.top = master
self.files = filelist
self.index = 0
#display first image
filename = filelist[0]
if not os.path.exists(filename):
print "Unable to find %s" % filename
self.top.quit()
self.title = Label(text=os.path.basename(filename))
self.title.pack()
im = Image.open(filename)
self.tkimage = ImageTk.PhotoImage(im, palette=256)
self.lbl = Label(master, image=self.tkimage)
self.lbl.pack(side='top')
# the button frame
fr = Frame(master)
fr.pack(side='top', expand=1, fill='both')
back = Button(fr, text="back", command=lambda : self.nextframe(-1))
back.grid(row=0, column=0, sticky="w", padx=4, pady=4)
self.ilabel = Label(fr, text="image number: %d/%d" %
(self.index+1, len(self.files)))
self.ilabel.grid(row=0, column=1, sticky="e", pady=4)
self.evar = IntVar()
self.evar.set(1)
next = Button(fr, text="next", command=lambda : self.nextframe(1))
next.grid(row=0, column=3, sticky="e", padx=4, pady=4)
# events
fr.focus_set()
fr.bind("<Key>", self.key)
fr.bind("<Button 1>", self.left_click)
def left_click(self, event):
print (event.x,event.y)
def key(self, event):
if event.char == 'z':
# previous frame
self.nextframe(-1)
elif event.char == 'x':
# next frame
self.nextframe(1)
elif event.char == 'q':
# quit
self.top.quit()
def getImage(self, filename):
im = Image.open(filename)
return im
def nextframe(self,i=1, imgnum=-1):
if imgnum == -1:
self.index += i
else:
self.index = imgnum - 1
if self.index >= len(self.files):
self.index = 0
elif self.index < 0:
self.index = len(self.files) - 1
filename = self.files[self.index]
if not os.path.exists(filename):
print "Unable to find %s" % filename
self.top.quit()
self.title.configure(text=os.path.basename(filename))
self.evar.set(self.index+1)
self.ilabel.configure(text="image number: %d/%d" %
(self.index+1, len(self.files)))
im = self.getImage(filename)
self.tkimage.paste(im)
def getimgnum(self, event=None):
self.nextframe(imgnum=self.evar.get())
# --------------------------------------------------------------------
if __name__ == "__main__":
if not sys.argv[1:]:
print "Usage: click.py images*"
sys.exit()
filelist = sys.argv[1:]
root = Tk()
app = Clicker(root, filelist)
root.mainloop()
The code should work with any set of images, all of which have to have the same dimensions.
Edit: Interestingly, I can get the cursor position on a key stroke but not on a mouse click.
It seems like I found the answer myself:
If I replace the Frame with a Canvas, I am able to trigger a mouse click event. I am not sure why that is the case, but it works.

Display output from functions called by buttons placed on GUI

I've tried to search this topic up, but it has been very confusing, as I don't use/quite understand stdout/stderr... However, I have this code right now that prints a list onto the console. Can someone explain to me how I could get this to print directly onto a GUI Textbox? My code:
from tkinter import *
import math
class TimeGenerator:
def __init__(self,master):
frame = Frame(master)
frame.grid()
label_iso = Label(root, text="Isotope A, Element")
label_vol = Label(root, text="Voltage")
label_range = Label(root, text="Charge Range")
entry_iso = Entry(root)
entry_vol = Entry(root)
entry_range = Entry(root)
label_iso.grid(row=0, sticky=E)
label_vol.grid(row=1, sticky=E)
label_range.grid(row=2, sticky=E)
entry_iso.grid(row=0, column=1)
entry_vol.grid(row=1, column=1)
entry_range.grid(row=2,column=1)
button = Button(root, text='Time Range', command=self.calculateTime)
button.grid(row=3, columnspan=2)
self.iso = entry_iso
self.vol = entry_vol
self.r = entry_range
def calculateTime(self):
x = 5
self.iso = self.iso.get().replace(" ", "")
list = []
for e in self.iso.split(","):
list.append(e)
f = open("/Users/LazyLinh/PycharmProjects/mass.mas12.txt", "r")
i = 0
while (i < 40):
header = f.readline()
i += 1
self.mass = 0
for line in f:
line = line.strip()
columns = line.split()
if (list[0] == columns[3]):
if (list[1] == columns[4]):
if (len(columns) == 16):
self.mass = float(columns[13].replace("#","")) + float(columns[14].replace("#",""))
else:
self.mass = float(columns[12].replace("#","")) + float(columns[13].replace("#",""))
self.r = self.r.get().replace(" ", "")
tup = tuple(int(x) for x in self.r.split(","))
list = []
for q in range(tup[0], tup[1] + 1):
y = x * math.sqrt(self.mass / (2 * q * float(self.vol.get())))
list.append(y)
i = tup[0]
for time in list:
print(i, ':', time)
i = i + 1
root = Tk()
b = TimeGenerator(root)
root.mainloop()
Thank you!
Somewhere in your code you need to create a text widget:
class TimeGenerator:
def __init__(self,master):
...
self.text = Text(...)
...
Later, use the insert method of the text widget instead of a print statement:
for time in list:
self.text.insert("end", "%d: %s\n" % (i, time))
i = i + 1

self.gridrange=8 is showing as a tuple when I want it to be an integer

#!/usr/bin/env python
import tkinter as tk
from tkinter import ttk
import math
import random
#positions are stored in label and number format
LARGE_FONT= ("Verdana", 12)
positions = ['label'+str(i)+str(j) for i in range(8) for j in range(8)]
class Application(tk.Frame):
global positions
def __init__(self, master=None):
tk.Frame.__init__(self, master)
self.grid(sticky=tk.N+tk.S+tk.E+tk.W)
#The entry screen
#label = tk.Label(self, text="""Begin.""", font=LARGE_FONT)
#label.grid(row=0, column=0, pady=10)
#label = tk.Label(self, text="""Exit.""", font=LARGE_FONT)
#label.grid(row=0, column=1, pady=10)
#button1 = ttk.Button(self, text="Start Game", command=self.start)
#button2 = ttk.Button(self, text="Quit Game", command=quit)
#button1.grid(row=1, column=0, pady=10)
#button2.grid(row=1, column=1, pady=1)
#def start(self):
#self.createWidgets()
self.master = master
app = tk.Frame(self.master, bg="yellow")
app.grid_rowconfigure(0, weight=1)
app.grid_columnconfigure(1, weight=1)
app.grid_columnconfigure(0, weight=1)
#app.pack(fill="both", expand=True)
# instructions and fonts
self.instructions = "Find the hidden treasure!\n\nUse the arrow keys to select where to look, then press Enter to check. \
There is a 50/50 chance you will be told the distance from the treasure. Keep hunting until you find it. Good luck!"
# create instructions widget
self.info = tk.Text(app, padx=10, pady=10,width=15,bd=0, height=19, bg="yellow")
self.info.insert(1.0,self.instructions)
self.info.grid(row=0,column=0,sticky='N'+'E'+'S'+'W')
# create island widget
self.island = tk.Text(app, bg="cyan", padx=40, pady=40, width=15, height=9, bd=0)
self.island.insert(1.0, "ready")
self.island.grid(row=0,column=1, stick='N'+'E'+'S'+'W', rowspan=3)
# restart button
#self.restart_b = tk.Button(app, text="Restart", bg="red", command=self.begin)
#self.restart_b.grid(row=2, column=0, pady=20)
# score labels and fields
self.score_lbl = tk.Label(app, text="Guesses: 0", bg="yellow")
self.score_lbl.grid(row=1, column=0)
#keep track og gold
self.gold_lbl = tk.Label(app, text="Gold: 0", bg="yellow")
self.gold_lbl.grid(row=3, column=0)
#gold and bandit positions
self.gridrange = 8
self.numchest = 10
self.bandits = 3
self.winscore = 100
# set keydown handler
root.bind("<Key>", self.key_pressed)
# best score variable
self.best_score = 0
# begin game
#self.begin()
#print self.treasure_pos
self.mainMenu()
def mainMenu(self):
self.t = tk.Toplevel(self.master, backgroun='red')
self.t.wm_title("Main Menu")
self.l = tk.Label(self.t, text="Welcome to Treasure Hunt", background='red')
self.l.pack(side="top", fill="both", expand=True, padx=100, pady=100)
self.t.lift(self.master)
#self.t.geometry('640x480+0+0')
self.play = tk.Button(self.t, text="play", bg="purple", command=self.letsplay)
self.play.pack(side='left', expand=True)
self.ops = tk.Button(self.t, text="options", bg="yellow", command=self.ops)
self.ops.pack(side='left', expand=True)
def ops(self):
self.opwin = tk.Toplevel(self.master, backgroun='red')
self.opwin.wm_title("Option Menu")
self.opl = tk.Label(self.opwin, text="Welcome to Treasure Hunt", background='red')
self.opl.pack(side="top", fill="both", expand=True, padx=100, pady=100)
self.opwin.lift()
#self.opwin.geometry('640x480+0+0')
self.appp = tk.Button(self.opwin, text="Apply", bg="purple", command=self.letsplay)
self.appp.pack(side='left', expand=True)
self.gridops = tk.Listbox(self.opwin, selectmode='SINGLE')
self.gridops.pack()
for i in range(6, 14):
self.gridops.insert(tk.END, i)
self.gridrange = self.gridops.curselection()
def letsplay(self):
self.t.destroy()
#self.opwin.destroy()
#self.begin()
self.createWidgets()
root.lift()
def createWidgets(self):
#print (self.gridrange)
root.lift()
root.after_cancel(self.tick)
self.matrix = [["#" for col in range(self.gridrange)] for row in range(self.gridrange)]
self.current_pos = [0,0]
self.treasure_pos = []
self.bandit_pos = []
#times treasure has been found
self.treasures_won = []
self.last_treasure = []
self.gold_found = 0
for i in range(0, self.numchest):
self.gold_xy = self.get_pos()
self.treasure_pos.append(self.gold_xy)
for i in self.treasure_pos:
print (i)
print (len(self.treasure_pos))
for i in range (0, self.bandits):
self.bandit_xy = self.get_pos()
self.bandit_pos.append(self.bandit_xy)
for i in self.bandit_pos:
print (i)
print (len(self.bandit_pos))
#self.treasure_pos = [0,0]
#print self.treasure_pos
self.sett()
top=self.winfo_toplevel()
self.entry_frame = tk.Frame(self)
self.entry_frame.grid(row=0, column=0,rowspan=1,columnspan=8,sticky=tk.N+tk.E+tk.W)
self.pos_frame = tk.Frame(self)
self.pos_frame.grid(row=1, column=0,columnspan=8,sticky=tk.N+tk.S+tk.E+tk.W)
self.entry_frame.rowconfigure(0,weight=2)
screenx=self.pos_frame.winfo_width()
screeny=self.pos_frame.winfo_height()
for i in range(8):
top.rowconfigure(i,weight=1)
top.columnconfigure(i,weight=1)
self.pos_frame.columnconfigure(i,weight=1)
self.pos_frame.rowconfigure(i,weight=1)
self.entry_frame.columnconfigure(i,weight=1)
self.rowconfigure(i,weight=1)
self.columnconfigure(i,weight=1)
self.label_no_of_moves=tk.Label(self.entry_frame,text="MOVES : ")
self.label_no_of_moves.grid(row=0,column=0,sticky=tk.N+tk.S+tk.E+tk.W)
self.moves=tk.StringVar()
self.number_of_moves=tk.Entry(self.entry_frame,textvariable=self.moves)
self.number_of_moves.grid(row=0,column=1,sticky=tk.N+tk.S+tk.E+tk.W)
self.label_direction=tk.Label(self.entry_frame,text="DIRECTION : ")
self.label_direction.grid(row=0,column=2,sticky=tk.N+tk.S+tk.E+tk.W)
#Assume Direction to be U D L R you can also use listbox here but i m not using it for saving time
self.dir=tk.StringVar()
self.direction=tk.Entry(self.entry_frame,textvariable=self.dir)
self.direction.grid(row=0,column=3,sticky=tk.N+tk.S+tk.E+tk.W)
self.direction=tk.Button(self.entry_frame,text='GO',command=self.gomoves)
self.direction.grid(row=0,column=4,sticky=tk.N+tk.S+tk.E+tk.W)
for i in range(8):
for j in range(8):
x='label'+str(i)+str(j)
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(3*(j+1))[0]+"7",text=str(i)+str(j))
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
#For updating the grid if window size is changed
self.bind('<Configure>',self.update)
#For initial Player position
self.start_position=str('label'+generate_initial_position())
self.current_position = self.start_position
print (self.current_position)
#initial position removed from positions(avaliable positions)
print (positions)
positions.remove(str(self.start_position))
#selecting treasure chest from remaining positions
self.treasure_chest_positions=random.sample(positions,10)
#removing treasures chest position from positions(avaliable positions)
for i in positions[:]:
if i in self.treasure_chest_positions:
positions.remove(i)
print (self.treasure_chest_positions)
#selecting bandits position from positions(avaliable positions)
self.bandit_positions =random.sample(positions,5)
def sett(self):
self.blink = False
self.guesses = 0
self.end_tick = False
self.tick()
def get_pos(self):
self.used = False
xy = random.randrange(self.gridrange), random.randrange(self.gridrange)
if xy in self.treasure_pos or xy in self.bandit_pos:
self.used = True
while self.used == True:
xy = (random.randrange(self.gridrange), random.randrange(self.gridrange))
if xy not in self.treasure_pos or xy in self.bandit_pos:
self.used = False
return xy
else:
return xy
def gomoves(self,event=None):
print ('GO MOVES')
#Validate Moves so that the values of moves should lie inside the positions avaliable
print (self.moves.get())
print (self.dir.get())
#On moving update the current position variable
#Please deal with the position written in format label(row_no)(column_no) like label01 for row=0 and column=1 it will not be that difficult
current_row= int(self.current_position[5:6])
current_column=int(self.current_position[6:7])
print (current_row , current_column)
#now update the position based on moves if moves are invalid then pop up tkDialogBox search a little on google you will get help from there
#self.current_position =
def key_pressed(self, event):
if event.keysym == "Right" and self.current_pos[1] < 7:
self.current_pos[1] += 1
print("right")
elif event.keysym == "Left" and self.current_pos[1] > 0:
self.current_pos[1] -= 1
print("left")
elif event.keysym == "Up" and self.current_pos[0] > 0:
self.current_pos[0] -= 1
print("up")
elif event.keysym == "Down" and self.current_pos[0] < 7:
self.current_pos[0] += 1
print("down")
elif event.keysym == "Return":
self.process_guess()
self.display_grid()
self.matrix = [["#" for col in range(8)] for row in range(8)] # is here the best place for this?
def check(self):
if self.current_pos_tuple in self.treasures_won:
self.counts = Counter(self.treasures_won)
print (self.counts)
print (self.counts)[self.current_pos_tuple]
if self.current_pos_tuple in self.last_treasure:
self.gold_found -= 10
self.treasures_won.remove(self.current_pos_tuple)
self.guesses -= 1
self.last_treasure.remove(self.current_pos_tuple)
print (self.last_treasure)
if self.counts[self.current_pos_tuple] > 3:
self.treasure_pos.remove(self.current_pos_tuple)
self.bandit_pos.append(self.current_pos_tuple)
print ('someone was here waiting for me')
self.gold_found -= 10
print (self.gold_found)
if self.gold_found >= self.winscore:
print ('you win')
if len(self.treasure_pos) <= 0:
print ('you lose')
def process_guess(self):
self.guesses += 1
self.score_lbl.config(text="Guesses: " + str(self.guesses))
self.current_pos_tuple = tuple(self.current_pos)
print (self.current_pos_tuple)
if self.current_pos_tuple in self.treasure_pos:
self.check()
print ('i think i see something shiney')
self.gold_found += 10
print (self.gold_found)
self.treasures_won.append(self.current_pos_tuple)
self.last_treasure.append(self.current_pos_tuple)
self.end_tick = True
self.gold_lbl.config(text="Gold: " + str(self.gold_found))
self.matrix[self.current_pos_tuple[0]][self.current_pos_tuple[1]] = "$"
self.display_grid()
elif self.current_pos_tuple in self.bandit_pos:
print ('something looks suspisious')
self.gold_found = 0
#if not (self.current_pos[0] == self.treasure_pos[0] and self.current_pos[1] == self.treasure_pos[1]):
#print "NOT HERE"
else:
randinteger = random.randrange(10)
dist = int(round(math.sqrt((self.current_pos[0] - self.treasure_pos[randinteger][0]) ** 2 + (self.current_pos[1] - self.treasure_pos[randinteger][1]) ** 2)))
self.matrix[self.current_pos[0]][self.current_pos[1]] = str(dist)
self.display_grid()
print (' i cant seem to find anything')
self.end_tick = True
def display_grid(self):
'''Displays current visual game state'''
self.island.delete(1.0, tk.END)
m_str = ""
for row in range(len(self.matrix)):
m_str += (" ".join(self.matrix[row]) + "\n")
self.island.insert(1.0, m_str)
def finish(self):
self.matrix[self.treasure_pos[self.current_pos_tuple][0]][self.treasure_pos[self.current_pos_tuple][1]] = "$"
self.display_grid()
self.island.insert(tk.END, " + 10 Gold!")
self.sett()
def update(self,event=None):
print (event.num)
screenx=self.pos_frame.winfo_width()
screeny=self.pos_frame.winfo_height()
for i in range(8):
for j in range(8):
x='label'+str(i)+str(j)
if x in self.treasure_chest_positions:
try:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text='Treasure')
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
except:
print("Treasure error")
elif x in self.bandit_positions:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text='Bandit')
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
elif x==self.current_position:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text='Current')
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
else:
self.x=tk.Label(self.pos_frame,bg="#"+"F"+str(5*(1+i))[0]+str(4*(i+1))[0]+str(6*(j+2))[0]+str(2*(j+1))[0]+"7",text=str(i)+str(j))
self.x.grid(row=i,column=j,sticky=tk.N+tk.S+tk.E+tk.W)
def tick(self):
'''timer for blinking cursor'''
if self.blink == False:
self.matrix[self.current_pos[0]][self.current_pos[1]] = "#"
elif self.blink == True:
self.matrix[self.current_pos[0]][self.current_pos[1]] = " "
self.blink = not self.blink
self.display_grid()
if not self.end_tick:
root.after(300, self.tick)
else:
self.sett()
def generate_initial_position():
pos=str(random.randint(0,7))+str(random.randint(0,7))
return pos
root = tk.Tk()
app = Application(root)
#app.master.title('Game')
root.mainloop()
I have a big problem because the code does not want to function while self.gridrange=8 is a tuple it needs to be an integer and I dont know what more you can do to make it an integer
This is the error
()
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Program Files\Python35\lib\tkinter\__init__.py", line 1549, in __call__
return self.func(*args)
File "C:\Users\Zero Davila\Desktop\new.py", line 110, in letsplay
self.createWidgets()
File "C:\Users\Zero Davila\Desktop\new.py", line 123, in createWidgets
self.matrix = [["#" for col in range(self.gridrange)] for row in range(self.gridrange)]
TypeError: 'tuple' object cannot be interpreted as an integer
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh() This is just so I could post on stack the h's
Your previous posts were incorrect. You did not assign self.gridrange as
self.gridrange = 8
You assign it as:
self.gridops = tk.Listbox(self.opwin, selectmode='SINGLE')
self.gridops.pack()
for i in range(6, 14):
self.gridops.insert(tk.END, i)
self.gridrange = self.gridops.curselection()
If you read through the information for Listbox.curselection() or the actual source code, you'll find that it returns a tuple. Hence your problem.
However, in the future, please create a Minimal, Complete, and Verifiable Example to help in debugging. It would have helped immensely.

Categories