My embarrassing and likely flame-able code (which will eventually turn into a chess game)
import chess
#from stockfish import Stockfish
import tkinter as tk
import time
board = chess.Board()
def boardtoarr(board): #converts chess board string to 2d array
boardlist = []
linelist = []
for b in range(0,128,2):
linelist.append(str(board)[b])
if len(linelist) == 8:
boardlist.append(linelist)
linelist = []
return boardlist
#given the square of a piece on the board, returns the legal squares the piece can move to
def piecelegalmoves(square,cboard):
ans = ''
for a in cboard.legal_moves:
a = str(a)
if a[0:2] == square:
ans += a[2::]+' '
return ans
def alllegalmoves(cboard):
x = str(cboard.legal_moves)[38:-2]
x = x.split(', ')
return x
squarevariable = ''
def squareclicked(event):
global squarevariable
print(topleftpixelstosquare(event.x,event.y))
print(lsquaretocsquare(topleftpixelstosquare(event.x,event.y)))
squarevariable = lsquaretocsquare(topleftpixelstosquare(event.x,event.y))
def topleftpixels(x,y): #returns top left pixel of given square
return [x*100,y*100]
def topleftpixelstosquare(x,y):
x = ('000' + str(x))
x = x[len(x)-3::]
y = ('000' + str(y))
y = y[len(y)-3::]
return [int(y[0]),int(x[0])]
def csquaretolsquare(square): #converts chess square notation to list square notation
ans = []
letterorder = 'abcdefgh'
ans.append(8-int(square[1]))
ans.append(letterorder.index(square[0]))
return ans
def lsquaretocsquare(square): #converts list square notation to chess square notation
ans = ''
letterorder = 'abcdefgh'
ans += (letterorder[square[1]])
ans += str(8-square[0])
return ans
def boardtoimage(root,boardstr): #places all pieces onto the window graphically
global wQueen,wKing,wKnight,wBishop,wPawn,wRook,bQueen,bKing,bKnight,bBishop,bPawn,bRook
for y in range(8):
for x in range(8):
piece = boardtoarr(boardstr)[y][x]
xcoord = topleftpixels(x,y)[0]
ycoord = topleftpixels(x,y)[1]
if piece == 'Q':
tk.Label(root, image = wQueen).place(x = xcoord,y = ycoord)
if piece == 'K':
tk.Label(root, image = wKing).place(x = xcoord,y = ycoord)
if piece == 'R':
tk.Label(root, image = wRook).place(x = xcoord,y = ycoord)
if piece == 'P':
tk.Label(root, image = wPawn).place(x = xcoord,y = ycoord)
if piece == 'B':
tk.Label(root, image = wBishop).place(x = xcoord,y = ycoord)
if piece == 'N':
tk.Label(root, image = wKnight).place(x = xcoord,y = ycoord)
if piece == 'q':
tk.Label(root, image = bQueen).place(x = xcoord,y = ycoord)
if piece == 'k':
tk.Label(root, image = bKing).place(x = xcoord,y = ycoord)
if piece == 'r':
tk.Label(root, image = bRook).place(x = xcoord,y = ycoord)
if piece == 'p':
tk.Label(root, image = bPawn).place(x = xcoord,y = ycoord)
if piece == 'b':
tk.Label(root, image = bBishop).place(x = xcoord,y = ycoord)
if piece == 'n':
tk.Label(root, image = bKnight).place(x = xcoord,y = ycoord)
def CMI_clicked(): #check if the chess menu image was clicked
global root
global BoardImage
for widget in root.winfo_children(): #code to clear page
widget.destroy()
boardbackground = tk.Label(root, image = BoardImage) #place the board image at the background
boardbackground.pack()
board.push_san('e2e4')
boardtoimage(root,str(board))
#while True:
#print('x')
#boardstr = str(board)
root.bind('<Button-1>', squareclicked)
def Menu():
global root
global ChessMenuImage
#Menu
ChessMenuOption = tk.Button(root ,image = ChessMenuImage, command = CMI_clicked) #create button using chess menu image and call function 'CMI_clicked' when pressed
ChessMenuOption.place(x = 380, y = 380) #place the chess menu image at given coordinates
root = tk.Tk()
ChessMenuImage = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\Chess_Selection_Image.png') #Load chess menu image file
BoardImage = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\ChessBoardImage.png') #Load board image file
#Piece image loading
#White
wQueen = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\wQueen.png')
wKing = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\wKing.png')
wPawn = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\wPawn.png')
wBishop = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\wBishop.png')
wKnight = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\wKnight.png')
wRook = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\wRook.png')
#Black
bQueen = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\bQueen.png')
bKing = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\bKing.png')
bPawn = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\bPawn.png')
bBishop = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\bBishop.png')
bKnight = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\bKnight.png')
bRook = tk.PhotoImage(file = r'C:\Users\benja\Documents\Python\Chess project\bRook.png')
root.geometry('800x800')
Menu()
root.mainloop()
lines 68-100 is where I'm placing the pieces, line 110 is where I'm placing the board as the background. However when I run the code it looks like this:
I know by running this code:
import tkinter as tk
win = tk.Tk()
photoimage = tk.PhotoImage(file=r'C:\Users\benja\Documents\Python\Chess project\wQueen.png')
width, height = photoimage.width(), photoimage.height()
canvas = tk.Canvas(win, bg="blue", width=width, height=height)
canvas.pack()
canvas.create_image(0, 0, image=photoimage, anchor='nw')
win.mainloop()
that python recognizes the pieces as transparent as it returns this
What am I doing wrong?
Since you have used Label widgets to show the images of the board and chess piece and Label does not support transparent background.
As your second example shows, you can use Canvas to show those transparent images. Below are the modified boardtoimage() and CMI_clicked() functions to use Canvas instead of Label:
...
def boardtoimage(root, boardstr): #places all pieces onto the window graphically
piece_mapping = {
'r': bRook, 'n': bKnight, 'b': bBishop, 'q': bQueen, 'k': bKing, 'p': bPawn,
'R': wRook, 'N': wKnight, 'B': wBishop, 'Q': wQueen, 'K': wKing, 'P': wPawn,
}
for y in range(8):
for x in range(8):
piece = boardtoarr(boardstr)[y][x]
# get the corresponding piece image
image = piece_mapping.get(piece, None)
if image:
xcoord = topleftpixels(x,y)[0]
ycoord = topleftpixels(x,y)[1]
# show the piece image
canvas.create_image(xcoord, ycoord, image=image, anchor="nw")
def CMI_clicked(): #check if the chess menu image was clicked
global canvas
for widget in root.winfo_children(): #code to clear page
widget.destroy()
# create the canvas to show those transparent images
canvas = tk.Canvas(root, width=BoardImage.width(), height=BoardImage.height(), highlightthickness=0)
canvas.pack()
# show the chess board image
canvas.create_image(0, 0, image=BoardImage, anchor="nw")
board.push_san('e2e4')
boardtoimage(root,str(board))
root.bind('<Button-1>', squareclicked)
...
Result:
Related
enter image description here
As you can see in the screenshot, my program has white lines on the left and top, how can I remove them? I would like them not to be there at all.
import ctypes as ct
from tkinter import *
def dark_title_bar(window):
window.update()
DWMWA_USE_IMMERSIVE_DARK_MODE = 20
set_window_attribute = ct.windll.dwmapi.DwmSetWindowAttribute
get_parent = ct.windll.user32.GetParent
hwnd = get_parent(window.winfo_id())
rendering_policy = DWMWA_USE_IMMERSIVE_DARK_MODE
value = 2
value = ct.c_int(value)
set_window_attribute(hwnd, rendering_policy, ct.byref(value), ct.sizeof(value))
win = Tk()
background_menu = PhotoImage(file="background-menu.png")
canvas_authorization = Canvas(win, width=1280, height=720)
canvas_authorization.grid()
canvas_authorization.create_image(640, 360, image=background_menu)
dark_title_bar(win)
win.geometry("1280x720")
win.geometry(str(win.winfo_width()+1) + "x" + str(win.winfo_height()+1))
#Returns to original size
win.geometry(str(win.winfo_width()-1) + "x" + str(win.winfo_height()-1))
win.geometry("1280x720")
win.mainloop()
This question already has answers here:
Setting background color of a tkinter ttk frame
(3 answers)
Closed 3 years ago.
I want to change the background of my ttk form (ceasar code script) to the color I have in my window = #FEFB22
I want to change the white "box" color to #FEFB22 click to see image !
from tkinter import *
from tkinter import ttk
# variables
letters="ABCDEFGHIJKLMNOPQRSTUVWXYZABCDEFGHIJKLMNOPQRSTUVWXYZ"
# fenetre
root = Tk()
#window title
root.title('Cesar Crypt/Decrypt par Maxence')
root.iconbitmap("logo.ico")
# allows for window to be resized
root.geometry("850x480")
# window background
root.configure(background='#FEFB22')
root.frame_header = ttk.Frame()
ttk.Label(root.frame_header, text = 'Code César', style = 'Header.TLabel').grid(row = 0, column = 1)
ttk.Label(root.frame_header, text = 'Entrez un nombre entre 1 et 25 :', style = 'Header.TLabel').grid(row = 1, column = 0)
ttk.Label(root.frame_header, text = 'Votre Message:', style = 'Header.TLabel').grid(row = 2, column = 0)
ttk.Label(root.frame_header, text='Votre message crypté/decrypté:',style='Header.TLabel').grid(row=4, column=0)
enc_dec_text = ttk.Entry(root.frame_header, width=110)
enc_dec_text.grid(row=4,column=1)
cipher_shift_menu = StringVar()
Spinbox(root.frame_header,from_=1, to=25, textvariable=cipher_shift_menu).grid(row=1, column=1)
text_entry = ttk.Entry(root.frame_header, width=100)
text_entry.grid(row=2,column=1)
def encrypt_text():
stringtoencrypt = text_entry.get()
stringtoencrypt = str(stringtoencrypt)
stringtoencrypt=stringtoencrypt.upper()
ciphershift = cipher_shift_menu.get()
ciphershift=int(ciphershift)
stringencrypted=""
for character in stringtoencrypt:
position = letters.find(character)
newposition = position+ciphershift
if character in letters:
stringencrypted = stringencrypted + letters[newposition]
else:
stringencrypted = stringencrypted + character
enc_dec_text.insert(0, stringencrypted)
def decrypt_text():
stringtodecrypt = text_entry.get()
stringtodecrypt = str(stringtodecrypt)
stringtodecrypt=stringtodecrypt.upper()
ciphershift = cipher_shift_menu.get()
ciphershift=int(ciphershift)
stringdecrypted=""
for character in stringtodecrypt:
position = letters.find(character)
newposition = position-ciphershift
if character in letters:
stringdecrypted = stringdecrypted + letters[newposition]
else:
stringdecrypted = stringdecrypted + character
enc_dec_text.insert(0, stringdecrypted)
#add image
width = 200
lenght = 200
image = PhotoImage(file="logort.png")
#bouton image
button = Button(root, image=image, bg='#FEFB22', bd=0, relief=SUNKEN)
button.pack()
# boutous
encrypt_button = ttk.Button(root.frame_header,text='Encrypter',command = lambda: encrypt_text()).grid(row=3,column=0)
decrypt_button = ttk.Button(root.frame_header,text='Decrypter',command = lambda: decrypt_text()).grid(row=3,column=1)
#bouton q
# uitter
bouton_quitter = Button(root, text="Quitter !", command=root.quit, font=("Courrier", 20), bg='#000000', fg='#FEFB22')
bouton_quitter.pack(side=BOTTOM)
root.frame_header.pack()
root.mainloop()
You can use ttk.Style to change the frame background color:
s = ttk.Style()
s.configure('My.TFrame', background='#FEFB22')
root.frame_header = ttk.Frame(root, style='My.TFrame')
from tkinter import *
from random import *
from functools import partial
class Game:
def __init__(self):
self.root = Tk()
self.frame = Frame(width = 574, height = 574)
self.frame.grid(columnspan = 30, rowspan = 30)
self.minex = []
self.miney = []
self.clickx = 0
self.clicky = 0
blank = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\blank.gif')
for i in range(0,30):
for j in range(0,30):
button = Button(width = 15, height = 15, padx = 2, pady = 2, image = blank, command = partial(self.click, j, i))
button.grid(row = i, column = j)
self.mine_place()
self.root.mainloop()
def mine_place(self):
for i in range(0,15):
self.minex.append(randint(1,30))
self.miney.append(randint(1,30))
def click(self, j, i):
miss = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\miss.gif')
hit = PhotoImage(file = 'C:\\Users\\PC\\Desktop\\Python Programs\\Minesweeper\\hit.gif')
for k in range(0, len(self.minex)):
if j + 1 == self.minex[k] and i + 1 == self.miney[k]:
button = Button(image = hit)
button.grid(row = i, column = j)
else:
button = Button(image = miss)
button.grid(row = i, column = j)
app = Game()
In self.click, when I wish to create a button with this image I am given a blank image. If I create a button in init, the image comes out just fine. What is wrong?..............................................................
It looks like you're images are getting garbage collected you need to save a reference to the images after using PhotoImage.
ie - you create the image blank so save a reference as self.blank= blank and use image = self.hit
My function mapupdater isn't working. It seems tkinter isn't keeping a reference to the image. I tried storing the reference in an array, I tried what was suggester here How to update the image of a Tkinter Label widget?
Both don't work.
#-----Begin Global Declarations-----#
global futureonoff
futureonoff = True
#-----End Global Declarations-----#
#Create a new window
window = Tkinter.Tk()
window.wm_title("SpaceMass")
window.geometry("1000x1000")
window.self= Text(bg='black')
window.self.pack(fill="both", expand=True)
#updating map based on ISS location
def mapupdater():
global futureonoff
marker_list = []
timenowforcomputing = strftime("%Y-%m-%d %H:%M:%S", gmtime())
iss.compute(timenowforcomputing)
currentlong = iss.sublong
currentlat = iss.sublat
currentlongfloat= float(iss.sublong)
currentlatfloat= float(iss.sublat)
#convert radians to degrees with the equations 1 radian = 57.2957795 degrees
#TODO Learn how to use pi in python
currentlongfloat = round(currentlongfloat*57.2957795, 3)
currentlatfloat= round(currentlatfloat*57.2957795, 3)
print(currentlongfloat)
print(currentlatfloat)
if futureonoff == True:
futureintermenter = 0
while futureintermenter < len(long_list_3_orbits):
marker_list.append("markers=size:mid|label:F|color:blue|"+str(lat_list_3_orbits[futureintermenter])+","+str(long_list_3_orbits[futureintermenter])+"|")
futureintermenter = futureintermenter + 1
marker_list.append("markers=size:mid|label:S|color:red|"+str(currentlatfloat)+","+str(currentlongfloat)+"|")
toopenupdater = get_static_google_map("mymap2", center="42.950827,-122.108974", zoom=1, imgsize=(500,500), imgformat="gif", maptype="satellite", markers=marker_list)
#Code from https://stackoverflow.com/questions/6086262/python-3-how-to-retrieve-an-image-from-the-web-and-display-in-a-gui-using-tkint
uupdater = urllib.urlopen(toopenupdater)
raw_data_u = uupdater.read()
u.close()
b64_data_u = base64.encodestring(raw_data_u)
imgtoprint = Tkinter.PhotoImage(data=b64_data)
# from http://www.daniweb.com/software-development/python/threads/79337/putting-an-image-into-a-tkinter-thingy
# pick an image file you have .bmp .jpg .gif. .png
# load the file and covert it to a Tkinter image object
panel1.configure(image = imgtoprint)
panel1.image = imgtoprint
#updata map after 30 seconds
window.after(30000, mapupdater)
def togglemap():
global futureonoff
print(futureonoff)
if futureonoff == True:
futureonoff = False
else:
futureonoff = True
mapupdater()
print(futureonoff)
#text_file.configure(text=testing)
#Info about buttons http://effbot.org/tkinterbook/button.htm
#Parsing code from https://stackoverflow.com/questions/773797/updating-tkinter-labels-in-python
#settings for font, font size, pixel size, of the text in our GUI
#convert radians to degrees with the equations 1 radian = 57.2957795 degrees
#TODO Learn how to use pi in python
currentlongfloat = round(currentlongfloat*57.2957795, 3)
currentlatfloat= round(currentlatfloat*57.2957795, 3)
if futureonoff == True:
futureintermenter = 0
while futureintermenter < len(long_list_3_orbits):
marker_list.append("markers=size:mid|label:F|color:blue|"+str(lat_list_3_orbits[futureintermenter])+","+str(long_list_3_orbits[futureintermenter])+"|")
futureintermenter = futureintermenter + 1
marker_list.append("markers=size:mid|label:S|color:red|"+str(currentlatfloat)+","+str(currentlongfloat)+"|")
#places map into GUI
toopen = get_static_google_map("mymap2", center="42.950827,-122.108974", zoom=1, imgsize=(500,500), imgformat="gif", maptype="satellite", markers=marker_list)
#im = PIL.Image.open("mymap2.png")
#imageFile = "mymap2.png"
#Code from https://stackoverflow.com/questions/6086262/python-3-how-to-retrieve-an-image-from-the-web-and-display-in-a-gui-using-tkint
#print(toopen)
u = urllib.urlopen(toopen)
raw_data = u.read()
u.close()
b64_data = base64.encodestring(raw_data)
global imgtoprint
imgtoprint = Tkinter.PhotoImage(data=b64_data)
panel1 = Tkinter.Label(window, image=imgtoprint, bg='black')
panel1.pack(side='top', fill='both', expand='yes')
panel1.place(x=250, y=115)
b = Button(window, text="Browse for XML File", font=("Helvetica", 15), command=fileback, bg = 'black')
b.pack()
b.place(x=425,y=650)
c = Button(window, text="Toggle Orbit Prediction on Map", font=("Helvetica", 15), command=togglemap, bg = 'black')
c.pack()
c.place(x=425,y=850)
mapupdater()
window.mainloop()
I want to display the values in the text boxes, but i'm getting this error:
blue.set(B_mean1)
AttributeError: 'numpy.ndarray' object has no attribute 'set'
and my code is:
from Tkinter import Tk, Frame, BOTH
from Tkinter import *
import cv2
from collections import *
from CBIR import *
from experiment import *
from scipy.spatial import distance
import Tkinter,tkFileDialog
from PIL import Image, ImageTk
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent,background="light grey")
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("PISE")
self.pack(fill=BOTH, expand=1)
def open():
path=tkFileDialog.askopenfilename(filetypes=[("Image File",'.jpg')])
custName.set(path)
im = Image.open(path)
tkimage = ImageTk.PhotoImage(im)
myvar=Label(root,image = tkimage)
myvar.image = tkimage
myvar.pack()
myvar.place(x = 100, y = 100)
graylist1 = list()
resizelist1 = list()
eq_graylist1 = list()
cont_list1 = list()
ene_list1 = list()
homo_list1 = list()
cor_list1 = list()
B_mean1 = list()
G_mean1 = list()
R_mean1 = list()
dis_list1 = list()
imge = cv2.imread(path)
arr = array(imge)
g_img = cv2.imread(path,0)
gray_re_img = cv2.resize(g_img,(256,256))
graylist1.append(gray_re_img)
equ = cv2.equalizeHist(gray_re_img)
eq_graylist1.append(equ)
re_img = cv2.resize(imge,(256,256))
resizelist1.append(re_img)
blue, green, red = cv2.split(re_img)
total = re_img.size
B = sum(blue) / total
G = sum(green) / total
R = sum(red) / total
B_mean1.append(B)
G_mean1.append(G)
R_mean1.append(R)
im = skimage.io.imread(path, as_grey=True)
im = skimage.img_as_ubyte(im)
im /= 32
g = skimage.feature.greycomatrix(im, [1], [0], levels=8, symmetric=False, normed=True)
cont = skimage.feature.greycoprops(g, 'contrast')[0][0]
cont_list1.append(cont)
ene = skimage.feature.greycoprops(g, 'energy')[0][0]
ene_list1.append(ene)
homo = skimage.feature.greycoprops(g, 'homogeneity')[0][0]
homo_list1.append(homo)
cor = skimage.feature.greycoprops(g, 'correlation')[0][0]
cor_list1.append(cor)
dis = skimage.feature.greycoprops(g, 'dissimilarity')[0][0]
dis_list1.append(dis)
feature_matrix_ip = zip( B_mean1 , G_mean1 , R_mean1, cont_list1 , ene_list1 , homo_list1 , cor_list1 , dis_list1)
blue.set(B_mean1)
root = Tk()
root.geometry("1105x605+300+300")
app = Example(root)
label = Label(app, text='Python Image Search', fg = 'black',font = 'PoorRichard 24')
label.pack()
label.place(y = 5, x = 0)
img = Image.open('logo.png')
bg_img = ImageTk.PhotoImage(img)
label1 = Label(app, image = bg_img)
label1.place(y = 5, x = 1225)
custName = StringVar(None)
yourName = Entry(app, textvariable=custName)
yourName.grid(column=0,row=0,sticky='EW')
yourName.update()
yourName.focus_set()
yourName.pack(padx = 20, pady = 20,anchor='n')
yourName.place(y = 60, x = 100, width = 525, height = 25)
blue_label = Label(app,text = 'Blue Mean')
blue_label.place(x = 850,y = 140)
blue = IntVar()
blue_text = Entry(app,textvariable = blue)
blue_text.place(x = 1000,y = 140)
button = Button(app, text='Select an Image',command = open)
button.pack(padx = 1, pady = 1,anchor='ne')
button.place( x = 650, y = 60)
root.mainloop()
All I want to know is how to display the values into the textbox. Any suggestions are welcome.
Thanks in advance!
Your problem is that you are using the variable name blue for two different things. At one point it's a numpy array and at another it is an IntVar. When you call blue.set(...), you are doing that at the point where blue references a numpy array, hence the error message 'numpy.ndarray' object has no attribute 'set'
Try changing the name of your IntVar to something else, such as blue_var, and make sure you change it everywhere.