How can I fix the ball from going through the brick at start of game?
The pink ball is going through brick boundary at beginning of game, after it returns and hits the paddle it detects brick boundary.
from tkinter import *
import random
import time
color1 = 0
tk = Tk()
tk.title("Bounce!")
tk.resizable(0, 0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=500, height=500, bg="white", bd=0,
highlightthickness=0)
canvas.pack()
tk.update()
ball creation class
class Ball:
def __init__(self, canvas, paddle, brick, color):
self.canvas = canvas
self.paddle = paddle
self.brick = brick
self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id, 245, 100)
start = [-3, -2, -1, 0, 1, 2, 3]
random.shuffle(start)
self.x = start[0]
self.y = -3
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
self.hit_bottom = False`
gets update when paddle gets hit to send the ball back up
def hit_paddle(self, pos):
paddle_pos = self.canvas.coords(self.paddle.id)
if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
return True
return False
gets update when brick is hit to change color
def hit_brick(self, pos):
brick_pos = self.canvas.coords(self.brick.id)
if pos[0] >= brick_pos[0] and pos[2] <= brick_pos[2]:
if pos[1] <= brick_pos[3] and pos[1] == brick_pos[3]:
return True
return False
movement update for ball and brick change color update when brick is hit
def draw(self):
self.canvas.move(self.id, self.x, self.y)
pos = self.canvas.coords(self.id)
#print(pos)
global color1
brick update if statement, I added a print statment to see how many times it counts brick as getting hit at start of game and it returns the value 1 2 as soon as it hits the brick.
if self.hit_brick(pos):
self.y = 1
color1 = color1 + 1
print(color1)
if color1 == 4:
brick.draw()
if pos[1] <= 0:
self.y = 1
if pos[3] >= self.canvas_height:
self.hit_bottom = True
canvas.create_text(245, 100, text="Game Over")
if pos[0] <= 0:
self.x = 1
if pos[2] >= self.canvas_width:
self.x = -1
if self.hit_paddle(pos):
self.y = -1`
paddle creation class
class Paddle:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color)
self.canvas.move(self.id, 200, 300)
self.x = 0
self.canvas_width = self.canvas.winfo_width()
self.canvas.bind_all("<KeyPress-Left>", self.turn_left)
self.canvas.bind_all("<KeyPress-Right>", self.turn_right)
Paddle Controls
def draw(self):
self.canvas.move(self.id, self.x, 0)
pos = self.canvas.coords(self.id)
if pos[0] <= 0:
self.x = 0
if pos[2] >= self.canvas_width:
self.x = 0
def turn_left(self, evt):
self.x = -2
def turn_right(self, evt):
self.x = 2
class Brick:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_rectangle(0, 0, 500, 10, fill=color)
def draw(self):
self.canvas.itemconfig(self.id, fill="red")
brick = Brick(canvas, "Pink")
paddle = Paddle(canvas, "Blue")
ball = Ball(canvas, paddle, brick, 'pink')
while 1:
if ball.hit_bottom == False:
ball.draw()
paddle.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.01)
tk.mainloop()
At start of game ball should bounce off of pink brick but goes straight through and bounces back.
See also questions close to this topic
-
How do I take only specified required columns from CSV file and add into a table in postgresql?
Consider I have
*----*------*-----------*----------*----------*---------------*----------------* | id | name | addressid | address1 | address2 | attendancekey | attendancedate | *----*------*-----------*----------*----------*---------------*----------------*
columns in CSV file and I want only
id, name to be imported in student table and
addressid, address1, address2 to be imported in address table and
attendancekey and attendancedate to be imported in attendance table in database.
What query to be used to import the required columns into the table?
Database Postgresql Version - 12
Python Version - 3.4.4
Psycopg2 Version - 2.7.5
-
Minimizing SQL OLE calls to Python Socket - Removing headers
I currently have a Service written in Python that accepts web calls and returns information. Since these are fully formatted web calls there are http headers in both the request and the response. These calls are made frequently and in bulk. Due to the size of the request and response, the headers make up nearly 50% of our network traffic.
Since this is not a service being exposed to the clients I am looking to transmit only the request (123) and return the response (456). The code below has been designed to demonstrate the basic techniques and give an example of the issue. It is not indicative of our full process.
Simple Python Socket:
import socket MAX_PACKET = 32768 PORT = 9879 IP = '127.0.0.1' def open_sockets(): current_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) current_socket.bind((IP, PORT)) print(f"Socket bound to I.P. {IP} : port {PORT}") current_socket.listen(5) print("Open sockets - Socket is listening") print("-" * 80) while True: client_socket, address = current_socket.accept() request = client_socket.recv(MAX_PACKET).decode("utf-8") print(request) response_text = 456 response_to_send = f'HTTP/1.0 200 OK \nContent-Type: text/html \n\n{response_text}'.encode('utf-8') client_socket.send(response_to_send) client_socket.close() if __name__ == '__main__': open_sockets()
OLE Call from SQL (SQL Server 2016)
DECLARE @URL NVARCHAR(MAX) , @ret INT , @token INT; SET @URL = N'http://127.0.0.1:9879/request=123'; EXECUTE @ret = sp_OACreate 'MSXML2.ServerXMLHTTP', @token OUTPUT; IF @ret <> 0 RAISERROR('Unable to create HTTP connection.', 10, 1); EXECUTE @ret = sp_OAMethod @token, 'open', NULL, 'GET', @URL, False; IF @ret <> 0 RAISERROR('Unable to open HTTP connection.', 10, 1); EXECUTE @ret = sp_OAMethod @token, 'send'; IF @ret <> 0 RAISERROR('Unable to send HTTP command.', 10, 1); EXECUTE @ret = sp_OAGetProperty @token, 'responseText'; IF @ret <> 0 RAISERROR('Unable to read from http.', 10, 1); EXEC sp_OADestroy @token;
While the socket is running, if I execute the SQL call I get the following results:
From Python:
Socket bound to I.P. 127.0.0.1 : port 9879 Open sockets - Socket is listening -------------------------------------------------------------------------------- GET /request=123 HTTP/1.1 Connection: Keep-Alive Accept: */* Accept-Language: en-GB,en;q=0.5 User-Agent: Mozilla/4.0 (compatible; Win32; WinHttp.WinHttpRequest.5) Host: 127.0.0.1:9879
From SQL:
Column1 ------- 456 (1 row affected)
As you can see the content being is only a minor part of the data. And while the "real-world" calls and responses are a bit larger, the header info is a significant proportion. Especially on the request. In this case message length is 192 characters, of which 3 characters are actual content.
Is there a more efficient call, ole component object, access method etc. available in SQL to help me minimize the network traffic?
-
Is there any way to reference the current iteration of a comprehension?
I have a list of dictionaries that represent different individuals' answers to a survey, with each dictionary being a new person
{question:answer, etc.}
.I'm trying to only add a user's answer to their age on a survey as the value of a new dictionary only if they answered as being male or female in another question. D is the list of dictionaries and I want to traverse through the entire list but I don't know how to reference a specific dictionary while in the comprehension loop.
My goal is to do so so that I can check if the value of 'Gender' in the current dictionary is 'Male' and then add the answer to the age question to my new dictionary.
def train(D, gender, lookingFor): #lookingFor = ('Ageyears', 'Region') D1 = {} #gender = ['Male', 'Female'] D2 = {} for i in gender: for x in lookingFor: ageDict = [sub[x] for sub in D if D[***CURRENT ITERATION***][age] == i] D2[x] = dict.fromkeys(ageDict, 0) D1[i] = D2 print(D1)
I need to know what to put in place of
[***CURRENT ITERATION***]
so that I can reference the current dictionary.Here is the data:
[ OrderedDict([('Country', 'USA'), ('Region', 'OK'), ('Gender', 'Female'), ('Ageyears', 16), ('Handed', 'Right-Handed'), ('Height_cm', 169)]), OrderedDict([('Country', 'USA'), ('Region', 'GA'), ('Gender', 'Female'), ('Ageyears', 18), ('Handed', 'Left-Handed'), ('Height_cm', 165.1)]), OrderedDict([('Country', 'USA'), ('Region', 'NJ'), ('Gender', ''), ('Ageyears', ''), ('Handed', ''), ('Height_cm', '')]), ]
-
image is not getting displayed in tkinter canvas
I want to build a program that will pick an image and display it on canvas. it not displaying the image in the canvas. I have declared a canvas "photo that will view picked image but it is not working. i don't have much knowledge about Tkinter.
from tkinter import * from tkinter import filedialog from PIL import ImageTk, Image from tkinter import filedialog import os #creating the application main window. app = Tk() app.title("Multi-Language OCR") app.geometry("1200x600") def open_image(): global imagefile app.filename = filedialog.askopenfilename(initialdir="C:",title="Open image",filetypes=(("png files","*.png"),("all files","*.*"))) img = ImageTk.PhotoImage(Image.open(app.filename)) photo.create_image(0, 0, anchor=NW, image=img) #button defination button_0 = Button(app,text="Open Image",bg="black",fg="white",command=open_image) button_1 = Button(app, text="Bengali",bg="black",fg="white",width = "15") button_2 = Button(app, text="Gujrati",bg="black",fg="white",width = "15") button_3 = Button(app, text="Hindi",bg="black",fg="white",width = "15") button_4 = Button(app, text="Kannada",bg="black",fg="white",width = "15") button_5 = Button(app, text="Malyalam",bg="black",fg="white",width = "15") button_6 = Button(app, text="Marathi",bg="black",fg="white",width = "15") button_7 = Button(app, text="Nepali",bg="black",fg="white",width = "15") button_8 = Button(app, text="Punjabi",bg="black",fg="white",width = "15") button_9 = Button(app, text="Sanskrit",bg="black",fg="white",width = "15") button_10 = Button(app, text="Sindhi",bg="black",fg="white",width = "15") button_11 = Button(app, text="Tamil",bg="black",fg="white",width = "15") #canvas used to display image photo = Canvas(app,bg="black",width="400",height="550") #label used to print output text; output = Label(app,text="OCR text",bg="cyan",fg="white",) #grid button_0.grid(row=0,column=0,padx="5" ) photo.grid(row ="1",column="0",rowspan=11,padx="20") button_1.grid(row=1 ,column =1,padx=50) button_2.grid(row=2 ,column=1) button_3.grid(row=3 ,column = 1) button_4.grid(row=4 ,column = 1) button_5.grid(row=5 ,column = 1) button_6.grid(row=6 ,column = 1) button_7.grid(row=7 ,column = 1) button_8.grid(row=8 ,column = 1) button_9.grid(row=9 ,column = 1) button_10.grid(row=10 ,column = 1) button_11.grid(row=11 ,column = 1) output.grid(row=2,column = 2,rowspan=11) #Entering the event main loop app.mainloop()
-
OpenCV Image Processing GUI: TypeError: on_click_diff_per_button() takes 1 positional argument but 2 were given
I am creating an OpenCV GUI for Image Processing. I have two image file folder. One is the Sample Image folder and the other is a reference file folder. I am importing both images in the frame and sample frame with the help of
filedialog.askopenfilename
. Now it is showing in two different frames. I am trying to connect the elements of both the frames with the 3rd frame so that it can display the image difference between two images.While performing the operation, I am getting the following error:ERROR:
select button clicked upload button clicked select Sample button clicked upload Sample button clicked Exception in Tkinter callback Traceback (most recent call last): File "C:\Users\CTPL\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__ return self.func(*args) File "C:/Users/CTPL/PycharmProjects/TempMatching/OpenCV_GUI_try2.py", line 280, in <lambda> select_button = tk.Button(frame5, text='Difference', command=lambda: difference_button.on_click_diff_per_button(Difference_per_label)) TypeError: on_click_diff_per_button() takes 1 positional argument but 2 were given
The python script I have applied is as shown below:
I have highlighted the Error portion in the above image.
import tkinter as tk from tkinter import filedialog from tkinter import messagebox import glob import os import cv2 import numpy as np from PIL import Image from PIL import ImageTk from skimage.metrics import structural_similarity class Button: def __init__(self, root, frame2): self.root = root self.frame2 = frame2 self.radio_var = tk.IntVar() self.path_selected = 'none' self.paths = [] self.radio_handle = [] self.check_value = [] def on_click_select_button(self, fname_label): print('select button clicked') fileType = [('jpg/png file', ('*.jpg', '*.png'))] self.path_selected = filedialog.askopenfilename(filetypes=fileType) fname_label['text'] = os.path.basename(self.path_selected) def on_click_upload_button(self, path='None', image='None'): print('upload button clicked') if path == 'None': path = self.path_selected else: cv2.imwrite(path, image) if path in self.paths: messagebox.showerror('Upload Error', '"' + path + '"' + ' is already uploaded.') else: self.paths.append(path) self.create_radio_button(path) def on_click_show_button(self): print('showButton clicked') image = cv2.imread(self.paths[self.radio_var.get()]) file_name = os.path.basename(self.paths[self.radio_var.get()]) name, ext = os.path.splitext(file_name) path = 'images/' + name + '_' + ext # cv2.imwrite(path, image) self.open_image_window(path, image) def create_radio_button(self, path): image = cv2.imread(path) # image = cv2.resize(image,(120,120)) image = self.scale_to_height(image, 120) image_tk = self.to_tk_image(image) radio_button = tk.Radiobutton(self.frame2, image=image_tk, value=len(self.radio_handle), variable=self.radio_var) self.radio_var.set(0) self.radio_handle.append(radio_button) self.check_value.append(self.radio_var) radio_button.grid(row=(len(self.radio_handle) - 1) // 3, column=(len(self.radio_handle) - 1) % 3) self.root.mainloop() def open_image_window(self, path, image): if image.shape[0] > 300: image = self.scale_to_height(image, 300) img_win = tk.Toplevel(self.root) fname = os.path.basename(path) img_win.title(fname) img_canvas = tk.Canvas(img_win, width=image.shape[1], height=image.shape[0]) img_canvas.pack() image_tk = self.to_tk_image(image) img_canvas.create_image(0, 0, image=image_tk, anchor='nw') uploadButton2 = tk.Button(img_win, text='upload', command=lambda: self.on_click_upload_button(path, image)) uploadButton2.pack() self.root.mainloop() def to_tk_image(self, image_bgr): image_rgb = cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB) image_pil = Image.fromarray(image_rgb) image_tk = ImageTk.PhotoImage(image_pil) return image_tk def scale_to_height(self, img, height): scale = height / img.shape[0] return cv2.resize(img, dsize=None, fx=scale, fy=scale) class Sample_Button: def __init__(self, root, frame4): self.Sample_root = root self.frame4 = frame4 self.Sample_radio_var = tk.IntVar() self.Sample_path_selected = 'none' self.Sample_paths = [] self.Sample_radio_handle = [] self.Sample_check_value = [] def on_click_select_button_Sample(self, Sample_fname_label): print('select Sample button clicked') Sample_fileType = [('jpg/png file', ('*.jpg', '*.png'))] self.Sample_path_selected = filedialog.askopenfilename(filetypes=Sample_fileType) Sample_fname_label['text'] = os.path.basename(self.Sample_path_selected) def on_click_upload_button_Sample(self, Sample_path='None', Sample_image='None'): print('upload Sample button clicked') if Sample_path == 'None': Sample_path = self.Sample_path_selected else: cv2.imwrite(Sample_path, Sample_image) if Sample_path in self.Sample_paths: messagebox.showerror('Upload Error', '"' + Sample_path + '"' + ' Sample is already uploaded.') else: self.Sample_paths.append(Sample_path) self.create_Sample_radio_button(Sample_path) def on_click_show_button_Sample(self): print('show Sample Button clicked') Sample_image = cv2.imread(self.Sample_paths[self.Sample_radio_var.get()]) Sample_file_name = os.path.basename(self.Sample_paths[self.Sample_radio_var.get()]) Sample_name, ext = os.path.splitext(Sample_file_name) Sample_path = 'Sample_images/' + Sample_name + '_' + ext def create_Sample_radio_button(self, Sample_path): Sample_image = cv2.imread(Sample_path) Sample_image = self.scale_to_height_Sample(Sample_image, 120) Sample_image_tk = self.Sample_to_tk_image(Sample_image) Sample_radio_button = tk.Radiobutton(self.frame4, image=Sample_image_tk, value=len(self.Sample_radio_handle), variable=self.Sample_radio_var) self.Sample_radio_var.set(0) self.Sample_radio_handle.append(Sample_radio_button) self.Sample_check_value.append(self.Sample_radio_var) Sample_radio_button.grid(row=(len(self.Sample_radio_handle) - 1) // 3, column=(len(self.Sample_radio_handle) - 1) % 3) self.Sample_root.mainloop() def Sample_to_tk_image(self, Sample_image_bgr): Sample_image_rgb = cv2.cvtColor(Sample_image_bgr, cv2.COLOR_BGR2RGB) Sample_image_pil = Image.fromarray(Sample_image_rgb) Sample_image_tk = ImageTk.PhotoImage(Sample_image_pil) return Sample_image_tk def scale_to_height_Sample(self, Sample_img, height): scale = height / Sample_img.shape[0] return cv2.resize(Sample_img, dsize=None, fx=scale, fy=scale) class Difference_Button(Button, Sample_Button): def on_click_diff_per_button(self): print('select Difference button clicked') Sample_image = cv2.imread(self.Sample_paths[self.Sample_radio_var.get()]) print(Sample_image) image = cv2.imread(self.paths[self.radio_var.get()]) print(image) #for x in range(7): Greyscale_Sample_image = cv2.cvtColor(Sample_image, cv2.COLOR_RGB2GRAY) Greyscale_image = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY) (score, diff) = structural_similarity(Greyscale_image, Greyscale_Sample_image, full=True) # bw_ print("Image similarity %ge =", score * 100) diff = (diff * 255).astype("uint8") cv2.imshow('diff', diff) cv2.waitKey() pass if __name__ == '__main__': os.makedirs('images', exist_ok=True) root = tk.Tk() root.title('Image GUI') root.geometry('1280x960') pw_left = tk.Frame(root, relief='ridge', borderwidth=4) pw_left.pack(side='left', anchor='nw') pw_right = tk.Frame(root, relief='ridge', borderwidth=4) pw_right.pack(side='left', anchor='nw') frame1 = tk.Frame(pw_left, bd=2, relief="ridge") frame1.pack() frame2 = tk.LabelFrame(pw_right, bd=2, text='Uploaded images') frame2.pack(side='left', anchor='nw') button = Button(root, frame2) label = tk.Label(frame1, text='File:') label.grid(row=0, column=0) file_name_label = tk.Label(frame1, text='-----not selected-----', width=20, bg='white') file_name_label.grid(row=0, column=1) select_button = tk.Button(frame1, text='select', command=lambda: button.on_click_select_button(file_name_label)) select_button.grid(row=0, column=2) uploadButton = tk.Button(frame1, text='Upload', command=lambda: button.on_click_upload_button()) uploadButton.grid(row=0, column=3) os.makedirs('Sample_images', exist_ok=True) pw_left = tk.Frame(root, relief='ridge', borderwidth=4) pw_left.pack(side='left', anchor='nw') pw_right = tk.Frame(root, relief='ridge', borderwidth=4) pw_right.pack(side='left', anchor='nw') frame3 = tk.Frame(pw_left, bd=2, relief="ridge") frame3.pack() frame4 = tk.LabelFrame(pw_right, bd=2, text='Uploaded Sample images') frame4.pack(side='right', anchor='nw') Sample_button = Sample_Button(root, frame4) Sample_label = tk.Label(frame3, text='Sample File:') Sample_label.grid(row=0, column=0) Sample_file_name_label = tk.Label(frame3, text='-----not selected-----', width=20, bg='white') Sample_file_name_label.grid(row=0, column=1) Sample_select_button = tk.Button(frame3, text='select', command=lambda: Sample_button.on_click_select_button_Sample( Sample_file_name_label)) Sample_select_button.grid(row=0, column=2) Sample_uploadButton = tk.Button(frame3, text='Upload', command=lambda: Sample_button.on_click_upload_button_Sample()) Sample_uploadButton.grid(row=0, column=3) os.makedirs('Differece_images', exist_ok=True) pw_left = tk.Frame(root, relief='ridge', borderwidth=4) pw_left.pack(side='left', anchor='nw') pw_right = tk.Frame(root, relief='ridge', borderwidth=4) pw_right.pack(side='left', anchor='nw') frame5 = tk.Frame(pw_left, bd=2, relief="ridge") frame5.pack() frame6 = tk.LabelFrame(pw_right, bd=2, text='Uploaded images') frame6.pack(side='left', anchor='nw') difference_button = Difference_Button(root, frame6) Difference_per_label = tk.Label(frame5, text='Show Image Difference', width=20, bg='white') Difference_per_label.grid(row=0, column=1) img_diff_button = tk.Button(frame5, text='Difference', command=lambda: difference_button.on_click_diff_per_button(Difference_per_label)) img_diff_button.grid(row=0, column=2) root.mainloop()
Kindly help me in solving this issue.
-
how browse and show image in tkinter?
I tried for many days to browse and display an image from my computer location but it seems shows successfully uploaded message and store on location in my computer but when i click on Ok button on message box it might be invisible from window where it needs to display.
Traceback (most recent call last): File "C:/Users/Prathamesh/PycharmProjects/OSN_filter/browsecode.py", line 8, in <module> from PIL import Image ModuleNotFoundError: No module named 'PIL'
This is the code:
from tkinter import * import sqlite3 from tkinter import filedialog from tkinter import simpledialog from tkinter import messagebox from tkinter.filedialog import askopenfilename import os from PIL import Image root = Tk() root.geometry('500x400') root.title("User Profile") # declaring variables username = StringVar() cityname = StringVar() statename = StringVar() countryname = StringVar() specialinterests = StringVar() hobby = StringVar() def database(): uname = username.get() ucity1 = cityname.get() ustate = statename.get() ucountry = countryname.get() uinterests = specialinterests.get() uhobby = hobby.get() conn = sqlite3.connect('D:\\project_database\\osndb.sqlite') # database name with conn: cursor = conn.cursor() # cursor.execute('CREATE TABLE IF NOT EXISTS Student(Fullname TEXT,Email TEXT,Gender TEXT,country TEXT,Programming TEXT)') cursor.execute('INSERT INTO profiledetails(usrname,city,state,country,interests,hobbies)VALUES(?,?,?,?,?,?)',(uname,ucity1,ustate,ucountry,uinterests,uhobby)) conn.commit() def onOpen(): file=filedialog.askopenfilename() im=Image.open(file) if im.mode != "RGBA": im = im.convert("RGBA") txt = Image.new('RGBA',im.size,(255,255,255,0)) #file = filedialog.asksaveasfile(mode='w',defaultextension=".png",filetypes=(("PNG file","*.png"),("All Files","*.*"))) #if file: # path = os.fi(file.name) pname = username.get() abs_path = "D:\\project_database\\profile_pictures\\"+pname+".png" out = Image.alpha_composite(im,txt) out.save(abs_path) messageVar = Message(root,text='Profile picture is Saved',bg='lightgreen') resultk=messagebox.showwarning('',abs_path,icon="warning") result=messagebox.showwarning('','Profile Picture is saved',icon="warning") img = PhotoImage(file=r'C:\\Users\\Prathamesh\\Pictures\\docs\\newregister.png') # background image back_image = Label(root, image=img) back_image.image = img back_image.place(x=0, y=0, relwidth=1, relheight=1) img = PhotoImage(file=r'C:\\Users\\Prathamesh\\Pictures\\per.png').subsample(2,2) # profile picture imageL = Label(root,width=100, height=100,image=img).place(x=350,y=40) nameL = Label(root,text="Name",anchor=W,fg='white',bg="#32373D",font=('times new roman',14)).place(x=10,y=25) # label code nameT = Entry(root,width=20,textvar=username).place(x=135,y=25) # textbox code cityL = Label(root,text="City",anchor=W,fg='white',bg="#32373D", font=('times new roman',14)).place(x=10,y=50) cityT = Entry(root,width=20,textvar=cityname).place(x=135,y=50) stateL = Label(root,text="State",anchor=W,fg='white',bg="#32373D",font=('times new roman',14)).place(x=10,y=75) stateT = Entry(root,width=20,textvar=statename).place(x=135,y=75) countryL = Label(root,text="Country",anchor=W,fg='white',bg="#32373D",font=('times new roman',14)).place(x=10,y=100) countryT = Entry(root,width=20,textvar=countryname).place(x=135,y=100) interestL = Label(root,text="Special Interest",anchor=W,fg='white',bg="#32373D",font=('times new roman',14)).place(x=10,y=125) interestT = Entry(root,width=20,textvar=specialinterests).place(x=135,y=125) hobbyL = Label(root,text="Hobbies",anchor=W,fg='white',bg="#32373D",font=('times new roman',14)).place(x=10,y=150) hobbyT = Entry(root,width=20,textvar=hobby).place(x=135,y=150) save=Button(root,text="SAVE",fg='white',bg='brown',width=10,font=('times new roman',12),command=database).place(x=80,y=185) browse=Button(root,text="BROWSE",fg='white',bg='brown',font=('times new roman',12),command=onOpen).place(x=365,y=185) root.mainloop()
-
Is there a way to do text wrapping on a tkinter canvas?
I'm trying to make an input system on a tkinter canvas, and I'm not sure how to enable text wrapping, and I urgently need this. Is there a way to do it?
-
Slow updating when dragging widget on canvas
So I'm using Python 3.7 and tkinter. I wanted to be able to drag a frame or canvas across a larger canvas. I put the code together and that works well enough. The problem is that the dragging does not look particularly good. Let's say I drag a widget to the right - I lose the very right side as it's moving. It comes back of course when I stop, but there is definitely an issue here. If I drag down, I lose the bottom side momentarily. And the quicker I drag, the more that gets lost.
I wondered if it might be just my imagination, but I was able to add a border to a frame and tried that. Since the border was a different colour, I could see if it 'disappeared' during drag. Yes, it did.
Surely there's a way to make this look less... bad? Is tkinter even the right way to go? All I really want is to be able to drag a frame (or canvas) on a larger canvas and have it look somewhat smooth. But this is really noticeable and something I feel I should fix.
As requested, the dragging code:
class CanvasDragManager(): def __init__(self, canvasParent): self.InitialX = 0 self.InitialY = 0 self.CanvasParent = canvasParent self.CanvasWidgetID = -1 def addDraggable(self, widget, canvas_id): widget.bind("<ButtonPress-1>", self.on_start) widget.bind("<B1-Motion>", self.on_drag) widget.bind("<ButtonRelease-1>", self.on_drop) self.CanvasWidgetID = canvas_id def on_start(self, event): self.InitialX = event.x self.InitialY = event.y def on_drag(self, event): canvasX, canvasY = self.CanvasParent.coords(self.CanvasWidgetID) dragX = (event.x + canvasX) - self.InitialX dragY = (event.y + canvasY) - self.InitialY self.CanvasParent.coords(self.CanvasWidgetID, dragX, dragY) def on_drop(self, event): print('Dropped!')
-
tkinter: canvas.coordds combined with event.x and event.y
i'm trying to use canvas.move(widget, event.x, event.y) to be able to drag an object around in Tkinter.
i created the button first and then a window:
play_btn = Button(canvas, text = 'PLAY'...) play_btn_window = canvas.create_window(238, 450, window=play_btn)
the function for dragging is: (i added the print statements to check what was going wrong)
def move_button(event): canvas.move(play_btn_window, event.x, event.y) print('mouse at: ' , event.x, event.y) print('button at: ', canvas.coords(play_btn_window))
to bind it i used
game.bind("<B1-Motion>", move_button)
(because the main window is named game)
if i click anywhere EXCEPT on the button and drag it around it works, and the event.x and event.y match with canvas.coords. However, if i start by clicking on the button, it jumps around weirdly because event.x and event.y turn into relative coordinates. for example, if i click on the upper left corner on the button, event.x, event.y = 0,0 (the button could be anywhere on the canvas) -- and then it jumps to the upper left corner of the canvas and so on. is there any way I can detect WHEN the mouse is over the button? because then i can add an if statement and a formula that will convert the coordinates for me? or is there another way to get around this?