Help! I am using python 3.5.2 and the function self.new_game is not working. It is supposed to put text on the canvas but it does nothing! There are also no errors that appear in the shell.
from tkinter import *
import time
import os
WIDTH = 1920
HEIGHT = 1080
root = Tk()
root.state('zoomed')
planet_selected = 0
planet_name = "nothing"
planet_temp = -270
planet_size = 0.0
planet_life = 0.0
class Space(Frame):
def __init__(self):
Frame.__init__(self)
frame1 = Frame(self)
self.canvas = Canvas(frame1, width = WIDTH, height = HEIGHT, bg ="white")
self.canvas.focus_set()
self.canvas.create_text(1920,1000,text='Planetary Creator',font=('Arial',15))
self.master.title("Planetary Creator Alpha 0.1")
frame = Frame(root, bg='grey', width=1920, height=40)
frame.pack(fill='x')
button1 = Button(frame, text='New Game',command=lambda : self.new_game())
button1.pack(side='left', padx=10)
button2 = Button(frame, text='Quit Game',command=lambda : os._exit(0))
button2.pack(side='left')
#this function below does not work!!!
def new_game(self):
self.canvas.delete(ALL)
size = self.canvas.create_text(960,540,text=str(planet_size) + "moon",font=("Arial",10))
life = self.canvas.create_text(960,520,text="✣" + str(planet_life) + "%",font=("Arial",10))
temp = self.canvas.create_text(960,500,text=str(planet_temp) + "°C",font=("Arial",10))
name = self.canvas.create_text(960,480,text=planet_name,font=("Arial",15))
Space().mainloop()
I removed frame1 and put Canvas in root , and use canvas.pack() to see canvas in window.
(but I could use self instead of root and use self.pack() because Space inherits from Frame. it would ne more logical)
After that I had to only change text positions because windows was too big for my screen.
I used variables CENTER_X, CENTER_Y to put text in center regardless of the size of the screen.
from tkinter import *
import time
import os
class Space(Frame):
def __init__(self, master):
Frame.__init__(self, master)
self.master.title("Planetary Creator Alpha 0.1")
self.canvas = Canvas(root, width=WIDTH, height=HEIGHT, bg="white")
self.canvas.pack()
self.canvas.focus_set()
self.canvas.create_text(CENTER_X, CENTER_Y, text='Planetary Creator', font=('Arial',15))
frame = Frame(root, bg='grey', width=WIDTH, height=40)
frame.pack(fill='x')
button1 = Button(frame, text='New Game', command=self.new_game)
button1.pack(side='left', padx=10)
button2 = Button(frame, text='Quit Game', command=root.destroy)
button2.pack(side='left')
def new_game(self):
self.canvas.delete(ALL)
size = self.canvas.create_text(CENTER_X, CENTER_Y, text=str(planet_size) + "moon", font=("Arial",10))
life = self.canvas.create_text(CENTER_X, CENTER_Y-20, text="✣" + str(planet_life) + "%", font=("Arial",10))
temp = self.canvas.create_text(CENTER_X, CENTER_Y-40, text=str(planet_temp) + "°C", font=("Arial",10))
name = self.canvas.create_text(CENTER_X, CENTER_Y-60, text=planet_name, font=("Arial",15))
# --- main ---
WIDTH = 800 #1920
HEIGHT = 500 #1080
CENTER_X = WIDTH//2
CENTER_Y = HEIGHT//2
planet_selected = 0
planet_name = "nothing"
planet_temp = -270
planet_size = 0.0
planet_life = 0.0
root = Tk()
#root.state('zoomed')
Space(root)
root.mainloop()
Related
I am a beginner in Python. I created a GUI with nice buttons. To do this I did a change of images: when the mouse hovers the button and when the mouse leaves the button. I did this with this pretty ugly code, but it works:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.title("My first Python GUI")
root.geometry("1130x800")
canvas = Canvas(root, bg="#a9dfbf")
canvas.pack(fill=BOTH, expand=True)
button_1_onHover = Image.open("Buttons/button1_hover.png")
button_1_onLeave = Image.open("Buttons/button1_leave.png")
button_2_onHover = Image.open("Buttons/button2_hover.png")
button_2_onLeave = Image.open("Buttons/button2_leave.png")
root.button_1_onLeave = ImageTk.PhotoImage(button_1_onLeave)
root.button_1_onHover = ImageTk.PhotoImage(button_1_onHover)
root.button_2_onLeave = ImageTk.PhotoImage(button_2_onLeave)
root.button_2_onHover = ImageTk.PhotoImage(button_2_onHover)
def on_enter(event):
button1.config(image=root.button_1_onHover)
def on_leave(leave):
button1.config(image=root.button_1_onLeave)
def on_enter2(event):
button2.config(image=root.button_2_onHover)
def on_leave2(leave):
button2.config(image=root.button_2_onLeave)
button1 = Button(root, image=root.button_1_onLeave, bg="#a9dfbf", width=400, height=150, bd=0, relief="sunken", activebackground="#a9dfbf")
button2 = Button(root, image=root.button_2_onLeave, bg="#a9dfbf", width=400, height=150, bd=0, relief="sunken", activebackground="#a9dfbf")
canvas.create_window(300, 150, window=button1)
canvas.create_window(300, 350, window=button2)
button1.bind("<Enter>", on_enter)
button1.bind("<Leave>", on_leave)
button2.bind("<Enter>", on_enter2)
button2.bind("<Leave>", on_leave2)
root.mainloop()
This is the visual result:
visual result of the ugly code (it work)
BUT...
The problem is that to make a single button, it takes 15 lines of code.
If I want to create 10 buttons, it becomes incredibly repetitive and unpleasant.
Being a beginner, I heard about object-oriented programming, and so I turned my code into a class that I called NewButton:
from tkinter import *
from PIL import Image, ImageTk
class NewButton:
def __init__(self, imageHover, imageLeave, width, height, hposition, vposition):
self.root = Tk()
self.root.title("My first Python GUI")
self.root.geometry("1130x800")
canvas = Canvas(self.root, bg="#a9dfbf")
canvas.pack(fill=BOTH, expand=True)
self.width = width
self.height = height
self.hposition = hposition
self.vposition = vposition
self.imageHover = Image.open(f"Buttons/{imageHover}.png")
self.imageLeave = Image.open(f"Buttons/{imageLeave}.png")
self.root.imageLeave = ImageTk.PhotoImage(self.imageLeave)
self.root.imageHover = ImageTk.PhotoImage(self.imageHover)
self.button = Button(self.root, image=self.root.imageLeave, bg="#a9dfbf", width=self.width, height=self.height, bd=0, relief="sunken", activebackground="#a9dfbf")
canvas.create_window(self.hposition, self.vposition, window=self.button)
def on_enter(event):
self.button.config(image=self.root.imageHover)
def on_leave(leave):
self.button.config(image=self.root.imageLeave)
self.button.bind("<Enter>", on_enter)
self.button.bind("<Leave>", on_leave)
self.root.mainloop()
NewButton("button1_hover","button1_leave",400,150,300,150)
NewButton("button2_hover","button2_leave",400,150,300,350)
In the constructor of my class, I define the image used on hover, the image used on leave, the width of the button, its height, as well as the position of this button (horizontal position and vertical position).
Still in the constructor, I placed my 2 functions which change the image according to the enter/leave state.
Then I create my buttons as NewButton objects and give the characteristics of the button.
When I run my code, python creates the buttons for me, but in a different window.
This is the visual result:
result with POO code (not working)
What I want is to put all the buttons that I create on the same window, and that's not what I get with my code.
Can you tell me what's wrong?
Thank you (and sorry for my frenglish!)
SOLUTION by acw1668 that i try (it doesn't work):
His suggestion: "You need to create root and canvas outside the class and pass canvas to the class instance instead."
what I have done:
from tkinter import *
from PIL import Image, ImageTk
root = Tk()
root.title("My first Python GUI")
root.geometry("1130x800")
canvas = Canvas(root, bg="#a9dfbf")
canvas.pack(fill=BOTH, expand=True)
class NewButton:
def __init__(self, canvas, imageHover, imageLeave, width, height, hposition, vposition):
self.canvas = canvas
self.width = width
self.height = height
self.hposition = hposition
self.vposition = vposition
self.imageHover = Image.open(f"Buttons/{imageHover}.png")
self.imageLeave = Image.open(f"Buttons/{imageLeave}.png")
self.canvas.imageLeave = ImageTk.PhotoImage(self.imageLeave)
self.canvas.imageHover = ImageTk.PhotoImage(self.imageHover)
self.button = Button(self.canvas, image=self.canvas.imageLeave, bg="#a9dfbf", width=self.width, height=self.height, bd=0, relief="sunken", activebackground="#a9dfbf")
canvas.create_window(self.hposition, self.vposition, window=self.button)
def on_enter(event):
self.button.config(image=self.canvas.imageHover)
def on_leave(leave):
self.button.config(image=self.canvas.imageLeave)
self.button.bind("<Enter>", on_enter)
self.button.bind("<Leave>", on_leave)
self.canvas.mainloop()
NewButton(canvas,"button1_hover","button1_leave",400,150,300,150)
NewButton(canvas,"button2_hover","button2_leave",400,150,300,350)
You need to create root and canvas outside the class and then pass canvas to the class:
from tkinter import *
from PIL import Image, ImageTk
class NewButton:
def __init__(self, canvas, imageHover, imageLeave, width, height, hposition, vposition):
self.canvas = canvas
self.width = width
self.height = height
self.hposition = hposition
self.vposition = vposition
imageHover = Image.open(f"Buttons/{imageHover}.png")
imageLeave = Image.open(f"Buttons/{imageLeave}.png")
self.imageLeave = ImageTk.PhotoImage(imageLeave)
self.imageHover = ImageTk.PhotoImage(imageHover)
self.button = Button(canvas, image=self.imageLeave, bg="#a9dfbf", width=self.width, height=self.height, bd=0, relief="sunken", activebackground="#a9dfbf")
self.button.bind("<Enter>", self.on_enter)
self.button.bind("<Leave>", self.on_leave)
self.item_id = canvas.create_window(self.hposition, self.vposition, window=self.button)
def on_enter(self, event):
self.button.config(image=self.imageHover)
def on_leave(self, event):
self.button.config(image=self.imageLeave)
root = Tk()
root.title("My first Python GUI")
root.geometry("1130x800")
canvas = Canvas(root, bg="#a9dfbf")
canvas.pack(fill=BOTH, expand=True)
NewButton(canvas,"button1_hover","button1_leave",400,150,300,150)
NewButton(canvas,"button2_hover","button2_leave",400,150,300,350)
root.mainloop()
I am experimenting with Tkinter to build a simple UI. This will contain a similar structure to the below:
Menu
Settings
Action1
Etc...
I want Menu to be my main frame, and there to be some general stuff on there and then buttons to the other frames.
I have been using some code I found here as a baseline but my amendments failed to work as expected. For example, why do the Label's and Entry's I place not show?
Code is as follows:
import tkinter as tk
def raise_frame(frame):
frame.tkraise()
root = tk.Tk()
root.title("Name")
width=400
height=500
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
f1 = tk.Frame(root)
f2 = tk.Frame(root)
f3 = tk.Frame(root)
f4 = tk.Frame(root)
title = tk.Label(f1, text = "Title", background = '#3b5997', foreground ="white", font = ("Times New Roman", 25))
title.place(x=100,y=20,width=200,height=50)
eg1 = tk.Label(f1, text="Text :")
eg1.place(x=10,y=195,width=70,height=25)
eg2 = tk.Label(f1, text="Text")
eg2.place(x=290,y=195,width=70,height=25)
eg3 = tk.Entry(f1, width=20)
eg3.place(x=100,y=195,width=200,height=25)
raise_frame(f1)
root.mainloop()
I have used .grid() and pack() but never used place however I found the issue.
you need to use .place() for frame f1 as well, after the content that you want in that frame.
import tkinter as tk
def raise_frame(frame):
frame.tkraise()
root = tk.Tk()
root.title("Name")
width=400
height=500
screenwidth = root.winfo_screenwidth()
screenheight = root.winfo_screenheight()
alignstr = '%dx%d+%d+%d' % (width, height, (screenwidth - width) / 2, (screenheight - height) / 2)
root.geometry(alignstr)
root.resizable(width=False, height=False)
f1 = tk.Frame(root)
f2 = tk.Frame(root)
f3 = tk.Frame(root)
f4 = tk.Frame(root)
title = tk.Label(f1, text = "Title", background = '#3b5997', foreground ="white", font = ("Times New Roman", 25))
title.place(x=100,y=20,width=200,height=50)
eg1 = tk.Label(f1, text="Text :")
eg1.place(x=10,y=195,width=70,height=25)
eg2 = tk.Label(f1, text="Text")
eg2.place(x=290,y=195,width=70,height=25)
eg3 = tk.Entry(f1, width=20)
eg3.place(x=100,y=195,width=200,height=25)
f1.place(x=100,y=20,width=1000,height=900) # <-------------like this
raise_frame(f1)
root.mainloop()
When I create the scroll bar there seems to be no option to scroll even though the contents inside of it are bigger than the canvas.
The canvas is inside a frame as I heard this is the way to do this properly.
The relevant part of my code:
from tkinter import *
class UniversityProcessor:
def __init__(self):
self.root = Tk()
self.rootWidth, self.rootHeight = 1200, 1200
screenWidth, screenHeight = self.root.winfo_screenwidth(), self.root.winfo_screenheight()
xPosition, yPosition = (screenWidth/2) - (self.rootWidth/2), (screenHeight/2) - (self.rootHeight/2)
self.root.geometry("%dx%d+%d+%d"%(self.rootWidth, self.rootHeight, xPosition, yPosition))
self.root.title("University processor")
self.updateUniText()
self.root.mainloop()
def updateUniText(self):
self.textPixelTotal = 0
self.frame = Frame(self.root, bg = self.bg, width = self.rootWidth, height = self.rootHeight)
self.frame.pack()
self.canvas = Canvas(self.frame, bg = self.bg, width = self.rootWidth, height = self.rootHeight)
self.inner = Frame(self.canvas, bg = self.bg, width = self.rootWidth, height = self.rootHeight)
self.canvas.create_window((0, 0), window = self.inner, anchor = "nw")
for it in range(0, 50):
label = Label(self.inner, bg = self.bg, text = f"Title {it + 1}", font = ("Arial", 20, "bold"))
label.place(y = self.textPixelTotal, x = it)
self.canvas.update()
self.textPixelTotal += label.winfo_height()
self.inner.configure(height = self.textPixelTotal)
self.inner.place(x=0,y=0,anchor="nw")
self.scroll = Scrollbar(self.frame, orient = VERTICAL, command = self.canvas.yview)
self.scroll.pack(side = RIGHT, fill = Y)
self.canvas.configure(yscrollcommand = self.scroll.set)
self.canvas.bind("<Configure>", lambda e: self.canvas.configure(scrollregion = self.canvas.bbox("all")))
self.canvas.pack(side=LEFT, expand=True, fill=BOTH)
UniversityProcessor()
I have no idea if there's some kind of canvas property or scroll bar property I need to set but it fills the screen...
Scroll bar does appear, it's the correct size however no scrolling actually happens
You should not use place() to put labels inside canvas. You need to create an internal frame inside the canvas and put all the labels inside that frame:
def updateUniText(self):
textPixelTotal = 0
self.frame = Frame(self.root, width=self.rootWidth, height=self.rootHeight)
self.frame.pack()
self.background = Canvas(self.frame, width=self.rootWidth, height=self.rootHeight)
# an internal frame inside canvas
self.internal = Frame(self.background)
self.background.create_window(0, 0, window=self.internal, anchor="nw")
# create labels inside the internal frame
for i in range(0,200):
label = Label(self.internal, bg=self.bg, text=f"Title {i+1}", font=("Arial", 20, "bold"))
label.pack(anchor="w")
self.background.update()
self.scroll = Scrollbar(self.frame, orient=VERTICAL)
self.scroll.pack(side=RIGHT, fill=Y)
self.scroll.config(command=self.background.yview)
self.background.config(width=self.rootWidth-20, height=self.rootHeight)
self.background.config(yscrollcommand=self.scroll.set, scrollregion=self.background.bbox("all"))
self.background.pack(side=LEFT, expand=True, fill=BOTH)
I have this reproducible code, and I cannot understand why when I set the width value to 100 in the self.display_tcm_18 variable, it still does not increase its width. This self.display_tcm_18 lies within the self.xf Frame, which I set to a width value of 300 (wide enough to host a Label widget of 100). I don't know what I am missing in the Logic of building this GUI with tkinter. Does anyone could give me some hint?
import Tkinter
from Tkinter import *
import tkFileDialog
from tkFileDialog import askopenfilename
from tkFileDialog import askdirectory
class Window(Frame):
def __init__(self, master = None):
self.master = master
path = "logo.gif"
self.image = Tkinter.PhotoImage(file=path)
self.f = Frame(master, width=300, height =70)
self.sf = Frame(master, width=300, height=70)
self.xf = Frame(self.f,width = 300, relief=GROOVE, borderwidth = 2)
self.file_name_18 = ''
self.var = IntVar()
def browse_button():
filename = askopenfilename(filetypes = (("GEOTIFF Files", "*.tif"),))
self.file_name = filename
self.display.config(text = filename)
print(self.file_name)
self.Logo = Label(self.master, image = self.image).pack(side=TOP, padx=5)
self.open_tcm_button = Button(self.xf, text = "Open..", command = browse_button).pack(side=LEFT, padx = 5, pady = 10)
self.display_tcm_18 = Label(self.xf, width = 100, bg = "white", textvariable = self.file_name_18, relief = SUNKEN, anchor = W)
self.display_tcm_18.pack(side=LEFT)
self.tcm18_label = Label(self.f, text = "Tree Cover Mask 2018 ").place(relx=0.06, rely=0.125,anchor=W)
self.xf.place(relx=0.01, rely=0.125, anchor=NW)
self.f.pack(side=TOP)
root = Tk()
root.geometry("600x400")
app = Window(root)
root.mainloop()
I'm new to python and tkinter and I've been getting the error below whenever I try and add custom grid sizes to my program. I'm pretty sure this isn't a duplicate thread as in all other threads, none of them involve a grid or utilize the grid function within their issue.
TypeError: unsupported operand type(s) for /: 'int' and 'str' when making grid
The error I'm getting occurs whenever I try and change the vale of the GridSize within the GUI. You can change the value of it in the 'Change the settings of the treasure hunting game' part of the menu. I'm new to python so please put it in the simplest terms possible!
Here's my code:
import tkinter
import math
import random
from tkinter import *
import tkinter as tk
from tkinter import ttk
GridSizeSetByUser = '8x8'
choicesRows = ['8', '10', '12', '14']
v = choicesRows[0]
choicesColumns = ['8', '10', '12', '14']
v2 = choicesColumns[0]
GridRows = 9
GridColumns = 9
def getRows():
global GridRows
GridRows = GridRowSpinbox.get()
print(GridRows)
def getColumns():
global GridColumns
GridColumns = GridColumnSpinbox.get()
print(GridColumns)
def Treasure_Hunt_Window():
THunt = tk.Tk()
THunt.title("Treasure Hunt")
THuntInstructions = "Find the treasure hidden deep in the sand!Use ye arrow keys to move around,\n\n then press Space to search that spot! Keep searching until ye find it!"
board = GameBoard(THunt)
board.pack(side="top", fill="both", expand="true", padx=4, pady=4)
THunt.mainloop()
def Settings_Window():
Settings = tk.Tk()
Settings.title("Settings")
SettingsWelcome = tk.Label(Settings, text='Settings Menu', width=50, fg="magenta")
SettingsGridSize = tk.Label(Settings, text='Grid Size:', width =50, fg="magenta")
global mystring
mystring = StringVar()
global mystring2
mystring2 = StringVar()
global GridRowSpinbox
GridRowSpinbox = Spinbox(Settings, values=choicesRows, textvariable=mystring, width=50, state="readonly", fg="magenta")
SaveRowSize = tk.Button(Settings, text='Save row size for grid', width=50, fg="magenta", command = getRows)
global GridColumnSpinbox
GridColumnSpinbox = Spinbox(Settings, values=choicesColumns, textvariable=mystring2, state="readonly", width=50, fg="magenta")
SaveColumnSize = tk.Button(Settings, text='Save column size for grid', width=50, fg="magenta", command = getColumns)
SettingsBandits = tk.Label(Settings, text='Amount of Bandits:', width =50, fg="magenta")
BanditAmount = tk.Entry(Settings, width = 50, fg="magenta")
SettingsBandits = tk.Label(Settings, text='Amount of Treasure Chests (up to 64)', width =50, fg="magenta")
SettingsWelcome.pack(fill=X)
SettingsGridSize.pack(fill=X)
GridRowSpinbox.pack(fill=X)
SaveRowSize.pack(fill=X)
GridColumnSpinbox.pack(fill=X)
SaveColumnSize.pack(fill=X)
SettingsBandits.pack(fill=X)
BanditAmount.pack(fill=X)
def main():
root = tk.Tk()
root.title("Menu")
WelcomeButton = tk.Label(root, text='Welcome to the menu!', width=50, height=2, fg="magenta")
WelcomeButton.pack(fill=X)
StartButton = tk.Button(root, text='Start treasure hunting!', width=50, fg="magenta", command = Treasure_Hunt_Window)
StartButton.pack(fill=X)
SettingsButton = tk.Button(root, text='''Change the settings of the treasure hunting game.
This includes the grid size.''', width=50, fg="magenta", command = Settings_Window)
SettingsButton.pack(fill=X)
QuitButton = tk.Button(root, text='Exit the program', width=50, fg="magenta", command = root.destroy)# display message in a child window.
QuitButton.pack(fill=X)
root.mainloop()
def teststuff():
print(GridRows)
print(GridColumns)
class GameBoard(tk.Frame):
def __init__(self, parent, size=48, color1="white", color2="black"):
'''size is the size of a square, in pixels'''
self.rows = GridRows
self.columns = GridColumns
self.size = size
self.color1 = color1
self.color2 = color2
self.pieces = {}
canvas_width = GridColumns * size
canvas_height = GridRows * size
tk.Frame.__init__(self, parent)
self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0,
width=canvas_width, height=canvas_height, background="green")
self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2)
self.canvas.bind("<Configure>", self.refresh)
def refresh(self, event):
'''Redraw the board, possibly in response to window being resized'''
xsize = int((event.width-1) / self.columns)
ysize = int((event.height-1) / self.rows)
self.size = min(xsize, ysize)
self.canvas.delete("square")
color = self.color2
for row in range(self.rows):
color = self.color1 if color == self.color2 else self.color2
for col in range(self.columns):
x1 = (col * self.size)
y1 = (row * self.size)
x2 = x1 + self.size
y2 = y1 + self.size
self.canvas.create_rectangle(x1, y1, x2, y2, outline="black", fill=color, tags="square")
color = self.color1 if color == self.color2 else self.color2
for name in self.pieces:
self.placepiece(name, self.pieces[name][0], self.pieces[name][1])
self.canvas.tag_raise("piece")
self.canvas.tag_lower("square")
main()
Please continue working on your program, but replace your code with the following and work from there. You may also want to make it a practice to run your code through the PEP8 online website. Changes that were made to your code include ensuring that no errors or warnings were generated.
To answer your question, two of the functions down below do something slightly different from what your code originally did. Notice the first two functions, get_rows and get_columns. When getting information from a Spinbox, you need to convert the data into the correct type before using it.
from tkinter import *
import tkinter as tk
GridSizeSetByUser = '8x8'
choicesRows = ['8', '10', '12', '14']
v = choicesRows[0]
choicesColumns = ['8', '10', '12', '14']
v2 = choicesColumns[0]
GridRows = 9
GridColumns = 9
my_string = my_second_string = grid_row_spinbox = grid_column_spinbox = None
def get_rows():
global GridRows
GridRows = int(grid_row_spinbox.get())
print(repr(GridRows))
def get_columns():
global GridColumns
GridColumns = int(grid_column_spinbox.get())
print(repr(GridColumns))
def treasure_hunt_window():
t_hunt = tk.Tk()
t_hunt.title("Treasure Hunt")
# t_hunt_instructions = """\
# Find the treasure hidden deep in the sand!Use ye arrow keys to move around,
#
# then press Space to search that spot! Keep searching until ye find it!"""
board = GameBoard(t_hunt)
board.pack(side="top", fill="both", expand="true", padx=4, pady=4)
t_hunt.mainloop()
def settings_window():
global my_string, my_second_string, grid_row_spinbox, grid_column_spinbox
settings = tk.Tk()
settings.title("Settings")
settings_welcome = tk.Label(settings, text='Settings Menu', width=50,
fg="magenta")
settings_grid_size = tk.Label(settings, text='Grid Size:', width=50,
fg="magenta")
my_string = StringVar()
my_second_string = StringVar()
grid_row_spinbox = Spinbox(settings, values=choicesRows,
textvariable=my_string, width=50,
state="readonly", fg="magenta")
save_row_size = tk.Button(settings, text='Save row size for grid',
width=50, fg="magenta", command=get_rows)
grid_column_spinbox = Spinbox(settings, values=choicesColumns,
textvariable=my_second_string,
state="readonly", width=50, fg="magenta")
save_column_size = tk.Button(settings, text='Save column size for grid',
width=50, fg="magenta", command=get_columns)
# settings_bandits = tk.Label(settings, text='Amount of Bandits:',
# width=50, fg="magenta")
bandit_amount = tk.Entry(settings, width=50, fg="magenta")
settings_bandits = tk.Label(settings,
text='Amount of Treasure Chests (up to 64)',
width=50, fg="magenta")
settings_welcome.pack(fill=X)
settings_grid_size.pack(fill=X)
grid_row_spinbox.pack(fill=X)
save_row_size.pack(fill=X)
grid_column_spinbox.pack(fill=X)
save_column_size.pack(fill=X)
settings_bandits.pack(fill=X)
bandit_amount.pack(fill=X)
def main():
root = tk.Tk()
root.title("Menu")
welcome_button = tk.Label(root, text='Welcome to the menu!', width=50,
height=2, fg="magenta")
welcome_button.pack(fill=X)
start_button = tk.Button(root, text='Start treasure hunting!', width=50,
fg="magenta", command=treasure_hunt_window)
start_button.pack(fill=X)
settings_button = tk.Button(root, text='''\
Change the settings of the treasure hunting game.
This includes the grid size.''', width=50, fg="magenta",
command=settings_window)
settings_button.pack(fill=X)
# display message in a child window.
quit_button = tk.Button(root, text='Exit the program', width=50,
fg="magenta", command=root.destroy)
quit_button.pack(fill=X)
root.mainloop()
def test_stuff():
print(GridRows)
print(GridColumns)
class GameBoard(tk.Frame):
def __init__(self, parent, size=48, color1="white", color2="black"):
"""size is the size of a square, in pixels"""
self.rows = GridRows
self.columns = GridColumns
self.size = size
self.color1 = color1
self.color2 = color2
self.pieces = {}
canvas_width = GridColumns * size
canvas_height = GridRows * size
tk.Frame.__init__(self, parent)
self.canvas = tk.Canvas(self, borderwidth=0, highlightthickness=0,
width=canvas_width, height=canvas_height,
background="green")
self.canvas.pack(side="top", fill="both", expand=True, padx=2, pady=2)
self.canvas.bind("<Configure>", self.refresh)
def refresh(self, event):
"""Redraw the board, possibly in response to window resize"""
x_size = int((event.width-1) / self.columns)
y_size = int((event.height-1) / self.rows)
self.size = min(x_size, y_size)
self.canvas.delete("square")
color = self.color2
for row in range(self.rows):
color = self.color1 if color == self.color2 else self.color2
for col in range(self.columns):
x1 = (col * self.size)
y1 = (row * self.size)
x2 = x1 + self.size
y2 = y1 + self.size
self.canvas.create_rectangle(x1, y1, x2, y2, outline="black",
fill=color, tags="square")
color = self.color1 if color == self.color2 else self.color2
for name in self.pieces:
self.place_piece(name, self.pieces[name][0], self.pieces[name][1])
self.canvas.tag_raise("piece")
self.canvas.tag_lower("square")
def place_piece(self, name, a, b):
pass
if __name__ == '__main__':
main()