How to make a button in a game class with tkinter - python

I have been trying to make a button in a class with tkinter, but the button doesn't appear. The rest of the game is fine. I is just when i try to add a quit button in the game class it doesn't appear. I am using python 3.4.3 . I am make a game that you pop bubbles with a submarine. I have tried self.button_quit = tkinter.Button(window, text="Quit") and this is the class code:
class Game():
height = 500
width = 800
mid_x = width / 2
mid_y = height / 2
bonus_score = 700
bubble_chance = 10
gap = 100
time_limit = 30
speed = 0.01
def __init__(self):
self.score = 0
self.bonus = 0
self.window = tkinter.Tk()
self.window.title('Bubble Blaster')
self.canvas = tkinter.Canvas(self.window, width=self.width,
height=self.height, bg='darkblue')
self.end = time.time() + self.time_limit
Text(self.canvas,50,30,'TIME')
Text(self.canvas,150,30,'SCORE')
self.gui_score = Text(self.canvas,150,50)
self.gui_time = Text(self.canvas,50,50)
self.canvas.pack()
self.bubbles = list()
self.ship = Ship(self.canvas)
self.ship.move(self.mid_x, self.mid_y)
def coords_of(cid):
pos = c.coords(cid)
x = (pos[0] + pos[2]) / 2
y = (pos[1] + pos[3]) / 2
return x, y
def create_bubble(self):
x = self.width + self.gap
y = random.randint(0,self.height)
self.bubbles.append(Bubble(self.canvas,x,y))
def move_bubbles(self):
for bubble in self.bubbles:
bubble.move(-bubble.speed,0)
def destroy_bubble(self,bubble):
self.bubbles.remove(bubble)
bubble.destroy()
def clean_up_bubbles(self):
for bubble in self.bubbles:
if bubble.x < -self.gap:
self.destroy_bubble(bubble)
def buttons(self):
self.button1 = tkinter.Button(window, text="Quit")
self.button1.tkinter.pack()
def run(self):
while time.time() < self.end:
if random.randint(1, self.bubble_chance) == 1:
self.create_bubble()
self.move_bubbles()
self.clean_up_bubbles()
self.score += self.ship_bubble_collision()
if (int(self.score / self.bonus_score)) > self.bonus:
self.bonus += 1
self.end += self.time_limit
self.time_left = int(self.end - time.time())
self.update_gui()
self.window.update()
self.ship.step()
time.sleep(self.speed)
Text(self.canvas,self.mid_x, self.mid_y,'GAME OVER',
font=('Helvetica',30))
Text(self.canvas,self.mid_x, self.mid_y + 30,
'Score ' + str(self.score))
Text(self.canvas,self.mid_x, self.mid_y + 45,'Bonus Time ' +
str(self.bonus * self.time_limit))
input()
def distance(self,x1,y1,x2,y2):
return math.sqrt((x2-x1)**2+(y2-y1)**2)
def ship_bubble_collision(self):
points = 0
for bubble in self.bubbles:
distance = self.distance(self.ship.x,self.ship.y,\
bubble.x,bubble.y)
boundary = self.ship.radius + bubble.radius
if distance < boundary:
points += bubble.radius + bubble.speed
self.destroy_bubble(bubble)
return points
def update_gui(self):
self.gui_score.update(str(self.score))
self.gui_time.update(str(self.time_left))
if __name__ == '__main__':
Game().run()

Add
buttons()
Where you need it to be called. Buttons can't appear without being called!
If you need more info on def, click here.
Also for future questions, please elaborate on your question more. It is hard to tell exactly what you are asking.

Related

How can I put my timer into a label in another file(in my game)?

I am programming a minesweeper and I am stuck because I still have to add a timer. I was able to program one but I can only see it in my console. But i want it to be in my game so that someone who is playong can see the time.
Now how do I add my programmed timer to the game? Down here is my code the first one is for the cell with all the definitions the second one is the main part and the last part is my time. I still have two files called settings and utils but these aren‘t important for the problem…
from tkinter import Button, Label
import random
import settings
import ctypes
import sys
import time
import elapsed
class Cell:
all = []
cell_count = settings.CELL_COUNT
cell_count_label_object = None
def __init__(self,x, y, is_mine=False):
self.is_mine = is_mine
self.is_opened = False
self.is_mine_candidate = False
self.cell_btn_object = False
self.x = x
self.y = y
self.done = False
# Append the object to the Cell.all list
Cell.all.append(self)
def create_btn_object(self, location):
btn = Button(
location,
width=10,
height=3,
)
btn.bind('<Button-1>', self.left_click_actions ) # Left Click
btn.bind('<Button-3>', self.right_click_actions ) # Right Click
self.cell_btn_object = btn
#staticmethod
def create_cell_count_label(location):
lbl = Label(
location,
bg='aquamarine3',
fg='white',
text=f"Cells Left:{Cell.cell_count}",
font=("", 30)
)
Cell.cell_count_label_object = lbl
def left_click_actions(self, event):
if self.is_mine:
self.show_mine()
else:
if self.surrounded_cells_mines_length == 0:
for cell_obj in self.surrounded_cells:
cell_obj.show_cell()
self.show_cell()
# If Mines count is equal to the cells left count, player won
if Cell.cell_count == settings.MINES_COUNT:
ctypes.windll.user32.MessageBoxW(0, 'Congratulations! You won the game!', 'Game Over', 0)
# Cancel Left and Right click events if cell is already opened:
self.cell_btn_object.unbind('<Button-1>')
self.cell_btn_object.unbind('<Button-3>')
def get_cell_by_axis(self, x,y):
# Return a cell object based on the value of x,y
for cell in Cell.all:
if cell.x == x and cell.y == y:
return cell
#property
def surrounded_cells(self):
cells = [
self.get_cell_by_axis(self.x - 1, self.y -1),
self.get_cell_by_axis(self.x - 1, self.y),
self.get_cell_by_axis(self.x - 1, self.y + 1),
self.get_cell_by_axis(self.x, self.y - 1),
self.get_cell_by_axis(self.x + 1, self.y - 1),
self.get_cell_by_axis(self.x + 1, self.y),
self.get_cell_by_axis(self.x + 1, self.y + 1),
self.get_cell_by_axis(self.x, self.y + 1)
]
cells = [cell for cell in cells if cell is not None]
return cells
#property
def surrounded_cells_mines_length(self):
counter = 0
for cell in self.surrounded_cells:
if cell.is_mine:
counter += 1
return counter
def show_cell(self):
if not self.is_opened:
Cell.cell_count -= 1
self.cell_btn_object.configure(text=self.surrounded_cells_mines_length)
# Replace the text of cell count label with the newer count
if Cell.cell_count_label_object:
Cell.cell_count_label_object.configure(
text=f"Cells Left:{Cell.cell_count}"
)
# If this was a mine candidate, then for safety, we should
# configure the background color to SystemButtonFace
self.cell_btn_object.configure(
bg='SystemButtonFace'
)
# Mark the cell as opened (Use is as the last line of this method)
self.is_opened = True
def show_mine(self):
self.cell_btn_object.configure(bg='red')
ctypes.windll.user32.MessageBoxW(0, 'You clicked on a mine', 'Game Over', 0)
sys.exit()
def right_click_actions(self, event):
if not self.is_mine_candidate:
self.cell_btn_object.configure(
text = '🌸',
fg = 'red'
)
self.is_mine_candidate = True
else:
self.cell_btn_object.configure(
bg='SystemButtonFace'
)
self.is_mine_candidate = False
def time():
start_time = time.time()
while True:
if not self.is_opened:
elapsed_time = time.time() - start_time
print(int(elapsed_time))
#staticmethod
def randomize_mines():
picked_cells = random.sample(
Cell.all, settings.MINES_COUNT
)
for picked_cell in picked_cells:
picked_cell.is_mine = True
def __repr__(self):
return f"Cell({self.x}, {self.y})"
from tkinter import *
from cell import Cell
import settings
import utils
import elapsed
import time
root = Tk()
# Override the settings of the window
root.configure(bg="aquamarine3")
root.geometry(f'{settings.WIDTH}x{settings.HEIGHT}')
root.title("Minesweeper Game")
root.resizable(False, False)
top_frame = Frame(
root,
bg='aquamarine3',
width=settings.WIDTH,
height=utils.height_prct(15)
)
top_frame.place(x=0, y=0)
game_title = Label(
top_frame,
bg='aquamarine3',
fg='white',
text='Minesweeper Game',
font=('', 48)
)
game_title.place(
x=utils.width_prct(30), y=0
)
left_frame = Frame(
root,
bg='aquamarine3',
width=utils.width_prct(75),
height=utils.height_prct(75)
)
left_frame.place(x=0, y=utils.height_prct(25))
timer_title = Label(
left_frame,
bg = 'aquamarine3',
fg = 'white',
text = ('time:', command = cell.time)
)
timer_title.place(
x = 0, y = 100
)
center_frame = Frame(
root,
bg='aquamarine3',
width=utils.width_prct(75),
height=utils.height_prct(75)
)
center_frame.place(
x=utils.width_prct(25),
y=utils.height_prct(15),
)
for x in range(settings.GRID_SIZE):
for y in range(settings.GRID_SIZE):
c = Cell(x, y)
c.create_btn_object(center_frame)
c.cell_btn_object.grid(
column=x, row=y
)
# Call the label from the Cell class
Cell.create_cell_count_label(left_frame)
Cell.cell_count_label_object.place(
x=0, y=0
)
Cell.randomize_mines()
# Run the window
root.mainloop()
import time
time.gmtime(0)
start_time = time.time()
def timer():
while True:
elapsed_time = time.time()-start_time
print(int(elapsed_time))

How to make Undo and Redo for Slider Scale Value?

I have code below :
var = DoubleVar()
scale = Scale(root, variable = var, command=self.scalfunc, from_=4, to=40, width=40,tickinterval=0,orient=VERTICAL,length=300,highlightthickness=0, background='#333333', fg='grey', troughcolor='#333333', activebackground='#1065BF')
scale.pack(anchor=CENTER)
scale.place(x=SCwidth/1.2, y=SCheight/15)
and I have button UNDO and anther button REDO
I want when I click in that button I make the Slider Value undo or redo
This code enables the use of Control keys to change the master colors of a tkinter.tk window.
Changes to Scale are stored in list called memory using index int called counter.
Control-z will undo
Control-Z will redo
Control-x will clear the memory
It shouldn't be too difficult to modify it for your needs.
import tkinter as tk
class UndoRedo:
def __init__(self):
self.master = tk.Tk()
self.master.withdraw()
self.master.columnconfigure(0, weight = 1)
self.master.columnconfigure(1, weight = 1)
self.color = 15790320 # #f0f0f0 = SystemButtonFace
self.var = tk.IntVar(self.master, value = self.color)
self.label = tk.Label(self.master, anchor = tk.E)
self.label.grid(row = 0, column = 0, sticky = tk.NSEW)
self.clear() # define memory and counter
self.scroll = tk.Scale(
self.master, orient = "horizontal", resolution = 65793,
label = "Brightness Control", from_ = 0, to = 16777215,
variable = self.var, command = self.control)
self.scroll.grid(row = 1, column = 0, columnspan = 2, sticky = tk.EW)
for k, v in [
( "<Control-z>", self.undo ),
( "<Control-Z>", self.redo ),
( "<Control-x>", self.clear )]:
self.master.bind(k, v)
self.master.geometry("400x86")
self.master.update()
self.master.minsize(329, 86)
self.master.resizable(True, False)
self.master.deiconify()
def display(self):
col = "#" + ("000000" + hex(self.color)[2:])[~5:]
self.var.set(self.color)
self.label["text"] = col
self.master.tk_setPalette(col)
def control(self, n):
self.color = int(n)
self.display()
if self.color not in self.memory:
self.memory.append(self.color)
self.counter = self.counter + 1
def action(self):
self.color = self.memory[self.counter]
self.display()
def undo(self, ev = None):
if self.memory:
self.counter = max(0, self.counter - 1)
self.action()
def redo(self, ev = None):
if self.memory:
self.counter = min(len( self.memory ) - 1, self.counter + 1)
self.action()
def clear(self, ev = None):
self.memory, self.counter = [], 0
self.label["text"] = "cleared"
if __name__ == "__main__":
bright = UndoRedo()
bright.master.mainloop()
If I understand correctly, you could store all positions taken by the slider in a list and use an index pointer to manipulate where it is in the list.
silder_ind = 0
slider_positions = [4] # Or wherever you want to start by default
When the user changes the position of the slider
new_pos = slider.get_current_value() # whatever the appropriate API call is to get the current value
slider_positions.append(new_pos)
slider_ind += 1
When the user hits undo
if (slider_ind - 1) >= 0:
slider_ind -= 1
redo
if (slider_ind + 1) < len(slider_positions):
slider_ind += 1

How to change button colour back to original when clicked again

I'm trying to change the button colour to black when clicked then change it back to white when clicked again. I'm trying to make Game Of Life for a school project.
I tried if statements but it doesn't change back to white, maybe I missed something simple. Here is the code:
from tkinter import *
class GUI(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
master.title("Window") #Window title
self.pack()
master.geometry("1280x720") #Window size
self.button={}#Dictionary for buttons
self.create_button()
def create_button(self):
indexList =[i for i in range(1000)]
self._button = Button(self, bg='white')
print(self._button.cget('bg'))
xPos = 0
yPos = 0
for index in indexList:
if(yPos == 40):
xPos = xPos + 20
yPos = 0
if(xPos == 10):
yPos = 8
self._button = Button(self, height=2, width=4, command = lambda
i = index: self.changecolour(i))
self.button[index] = self._button
self._button.grid(row=xPos, column =yPos)
yPos = yPos + 1
def changecolour(self,index):
aList = []
for i in range(1000):
aList.append([i,0])
for i in aList:
if index == i[0]:
if 0 == i[1]:
self.button[index].configure(bg = 'black')
i[1] = 1
else:
self.button[index].configure(bg = 'white')
i[1] = 0
root = Tk()
game_gui = GUI(master=root)
game_gui.mainloop()
As you can see it changes the button colour to black and it should change it back to white when clicked again, but it seems to just ignore the if statement.
I think this is the problem:
aList is not a global list
aList is created in changecolour() as a local list each time the subroutine is run
this means that when you do i[1] = 1 or i[1] = 0 it only changes the local list- aList. When the subroutine is run again, a new aList is created as a new local list.
to solve the problem define aList in the main program and make it a global list:
from tkinter import *
class GUI(Frame):
def __init__(self, master=None):
Frame.__init__(self, master)
master.title("Window") #Window title
self.pack()
master.geometry("1280x720") #Window size
self.button={}#Dictionary for buttons
self.create_button()
def create_button(self):
indexList =[i for i in range(1000)]
self._button = Button(self, bg='white')
print(self._button.cget('bg'))
xPos = 0
yPos = 0
for index in indexList:
if(yPos == 40):
xPos = xPos + 20
yPos = 0
if(xPos == 10):
yPos = 8
self._button = Button(self, height=2, width=4, command = lambda
i = index: self.changecolour(i))
self.button[index] = self._button
self._button.grid(row=xPos, column =yPos)
yPos = yPos + 1
def changecolour(self,index):
#aList IS NO LONGER CREATED HERE
for i in range(1000):
aList.append([i,0])
for i in aList:
if index == i[0]:
if 0 == i[1]:
self.button[index].configure(bg = 'black')
i[1] = 1
else:
self.button[index].configure(bg = 'white')
i[1] = 0
global aList #MAKE IT A GLOBAL LIST
aList = [] #CREATE THE EMPTY aList LIST
root = Tk()
game_gui = GUI(master=root)
game_gui.mainloop()

Improving tkinter.ttk code

I am a fairly novice programmer and through coffee, google, and an immense loss of hair and fingernails have managed to write a very messy code. I am asking anyone to help me simplify the code if possible.
from tkinter import ttk
from tkinter import *
from tkinter.ttk import *
one = 0
why = 'Total Number: {}'
no = 0
clack = 0
click = 'Clicks: {}'
s = ttk.Style()
s.theme_use('clam')
s.configure('red.Vertical.TProgressbar', foreground = 'red', background = 'red')
s.configure('green.Vertical.TProgressbar', foreground = 'green', background = 'green')
s.configure('TButton', relief = 'groove')
def iround(x):
y = round(x) - .5
return int(y) + (y > 0)
class Application(ttk.Frame):
def __init__(self, master = None):
ttk.Frame.__init__(self, master)
self.grid()
self.createWidgets()
def Number(self):
global one
cost = 10*(self.w['to'])
if self.number['text'] == "Make Number go up":
self.number['text'] = one
if iround(self.w.get()) == 0:
one += 1
else:
one += iround(self.w.get())
self.number['text'] = one
if self.number['text'] >= cost:
self.buy['state'] = 'normal'
else:
self.buy['state'] = 'disabled'
self.number['text'] >= cost
self.progress['value'] = one
if self.number['text'] >= cost:
self.progress['style'] = 'red.Vertical.TProgressbar'
else:
self.progress['style'] = 'green.Vertical.TProgressbar'
def Buy(self):
global one
self.w['to'] += 1
cost = 10*(self.w['to'])
one = self.number['text'] = (one + 10 - cost)
self.buy['text'] = ('+1 to slider | Cost: {}'.format(cost))
if self.number['text'] < (cost):
self.buy['state'] = 'disabled'
self.progress['value'] = one
self.progress['maximum'] += 10
if self.number['text'] >= cost:
self.progress['style'] = 'red.Vertical.TProgressbar'
else:
self.progress['style'] = 'green.Vertical.TProgressbar'
def scaleValue(self, event):
self.v['text'] = 'Slider Bonus + ' + str(iround(self.w.get()))
def clicks(self, event):
global click
global clack
if self.Clicks['text'] == 'Clicks: 0':
clack += 1
self.Clicks['text'] = click.format(clack)
self.Clicks['text'] = click.format(clack)
clack += 1
def NumberVal(self, event):
global why
global no
if self.fun['text'] == "Total Number: 0":
self.fun['text'] = why.format(no)
if iround(self.w.get()) == 0:
no += 1
else:
no += iround(self.w.get())
self.fun['text'] = why.format(no)
def createWidgets(self):
self.number = Button(self, text = 'Make number go up', command = self.Number, width = 20, style = 'TButton')
self.number.grid(row = 1, column = 1)
self.number.bind('<ButtonRelease>', self.clicks, add = '+')
self.number.bind('<ButtonRelease>', self.NumberVal, add = '+')
self.buy = Button(self, text = '+1 to Slider | Cost: 10', command = self.Buy, width = 20, style = 'TButton')
self.buy.grid(row = 2, column = 1)
self.buy.config(state = 'disabled')
self.v = Label(self, text = 'Slider Bonus + 0', width = 20, anchor = 'center')
self.v.grid(row = 3, column = 3)
self.w = Scale(self, from_ = 0, to = 1, orient = 'horizontal')
self.w.grid(row = 3, column = 1)
self.w.bind('<Motion>', self.scaleValue)
self.progress = Progressbar(self, value = 0, orient = 'vertical', maximum = 10, mode = 'determinate')
self.progress.grid(row = 1, rowspan = 5, column = 2)
self.Clicks = Label(self, text = 'Clicks: 0', width = 20, anchor = 'center')
self.Clicks.grid(row = 1, column = 3)
self.fun = Label(self, text = 'Total Number: 0', width = 20, anchor = 'center')
self.fun.grid(row = 2, column = 3)
app = Application()
app.master.title('Number')
app.mainloop()

Transparent colors Tkinter

Is it possible to change the color of a frame background or any other widget to transparent light blue or any other transparent color?
Yes there is a way. Unfortunately it only works for the entire window (The window and all of the child widgets).
Here is a little demo I wrote up a while ago which does what you want, among other things.
Transparent Window Demo :
import Tkinter as Tk, re
class TransparentWin (Tk.Tk) :
''' Transparent Tk Window Class '''
def __init__ (self) :
Tk.Tk.__init__(self)
self.Drag = Drag(self)
''' Sets focus to the window. '''
self.focus_force()
''' Removes the native window boarder. '''
self.overrideredirect(True)
''' Disables resizing of the widget. '''
self.resizable(False, False)
''' Places window above all other windows in the window stack. '''
self.wm_attributes("-topmost", True)
''' This changes the alpha value (How transparent the window should
be). It ranges from 0.0 (completely transparent) to 1.0
(completely opaque). '''
self.attributes("-alpha", 0.7)
''' The windows overall position on the screen '''
self.wm_geometry('+' + str(439) + '+' + str(172))
''' Changes the window's color. '''
bg = '#3e4134'
self.config(bg=bg)
self.Frame = Tk.Frame(self, bg=bg)
self.Frame.pack()
''' Exits the application when the window is right clicked. '''
self.Frame.bind('<Button-3>', self.exit)
''' Changes the window's size indirectly. '''
self.Frame.configure(width=162, height=100)
def exit (self, event) :
self.destroy()
def position (self) :
_filter = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
pos = self.winfo_geometry()
filtered = _filter.search(pos)
self.X = int(filtered.group(4))
self.Y = int(filtered.group(6))
return self.X, self.Y
class Drag:
''' Makes a window dragable. '''
def __init__ (self, par, dissable=None, releasecmd=None) :
self.Par = par
self.Dissable = dissable
self.ReleaseCMD = releasecmd
self.Par.bind('<Button-1>', self.relative_position)
self.Par.bind('<ButtonRelease-1>', self.drag_unbind)
def relative_position (self, event) :
cx, cy = self.Par.winfo_pointerxy()
x, y = self.Par.position()
self.OriX = x
self.OriY = y
self.RelX = cx - x
self.RelY = cy - y
self.Par.bind('<Motion>', self.drag_wid)
def drag_wid (self, event) :
cx, cy = self.Par.winfo_pointerxy()
d = self.Dissable
if d == 'x' :
x = self.OriX
y = cy - self.RelY
elif d == 'y' :
x = cx - self.RelX
y = self.OriY
else:
x = cx - self.RelX
y = cy - self.RelY
if x < 0 :
x = 0
if y < 0 :
y = 0
self.Par.wm_geometry('+' + str(x) + '+' + str(y))
def drag_unbind (self, event) :
self.Par.unbind('<Motion>')
if self.ReleaseCMD != None :
self.ReleaseCMD()
def dissable (self) :
self.Par.unbind('<Button-1>')
self.Par.unbind('<ButtonRelease-1>')
self.Par.unbind('<Motion>')
def __run__ () :
TransparentWin().mainloop()
if __name__ == '__main__' :
__run__()
For what it's worth, here's an arguably more readable version of the code in #rectangletangle's answer that has been re-formatted to more closely adhere to PEP 8 - Style Guide for Python Code recommendations.
Except for a trivial modification to the way the Tkinter module is imported so it will work in both Python 2 and 3, all other executable code is identical to his.
try:
import tkinter as tk
except ImportError:
import Tkinter as tk
import re
class TransparentWin(tk.Tk):
""" Transparent Tkinter Window Class. """
def __init__(self):
tk.Tk.__init__(self)
self.Drag = Drag(self)
# Sets focus to the window.
self.focus_force()
# Removes the native window boarder.
self.overrideredirect(True)
# Disables resizing of the widget.
self.resizable(False, False)
# Places window above all other windows in the window stack.
self.wm_attributes("-topmost", True)
# This changes the alpha value (How transparent the window should be).
# It ranges from 0.0 (completely transparent) to 1.0 (completely opaque).
self.attributes("-alpha", 0.7)
# The windows overall position on the screen
self.wm_geometry('+' + str(439) + '+' + str(172))
# Changes the window's color.
bg = '#3e4134'
self.config(bg=bg)
self.Frame = tk.Frame(self, bg=bg)
self.Frame.pack()
# Exits the application when the window is right clicked.
self.Frame.bind('<Button-3>', self.exit)
# Changes the window's size indirectly.
self.Frame.configure(width=162, height=100)
def exit(self, event):
self.destroy()
def position(self):
_filter = re.compile(r"(\d+)?x?(\d+)?([+-])(\d+)([+-])(\d+)")
pos = self.winfo_geometry()
filtered = _filter.search(pos)
self.X = int(filtered.group(4))
self.Y = int(filtered.group(6))
return self.X, self.Y
class Drag:
""" Makes a window draggable. """
def __init__(self, par, dissable=None, releasecmd=None):
self.Par = par
self.Dissable = dissable
self.ReleaseCMD = releasecmd
self.Par.bind('<Button-1>', self.relative_position)
self.Par.bind('<ButtonRelease-1>', self.drag_unbind)
def relative_position(self, event):
cx, cy = self.Par.winfo_pointerxy()
x, y = self.Par.position()
self.OriX = x
self.OriY = y
self.RelX = cx - x
self.RelY = cy - y
self.Par.bind('<Motion>', self.drag_wid)
def drag_wid(self, event):
cx, cy = self.Par.winfo_pointerxy()
d = self.Dissable
if d == 'x':
x = self.OriX
y = cy - self.RelY
elif d == 'y':
x = cx - self.RelX
y = self.OriY
else:
x = cx - self.RelX
y = cy - self.RelY
if x < 0:
x = 0
if y < 0:
y = 0
self.Par.wm_geometry('+' + str(x) + '+' + str(y))
def drag_unbind(self, event):
self.Par.unbind('<Motion>')
if self.ReleaseCMD != None:
self.ReleaseCMD()
def dissable(self):
self.Par.unbind('<Button-1>')
self.Par.unbind('<ButtonRelease-1>')
self.Par.unbind('<Motion>')
def __run__():
TransparentWin().mainloop()
if __name__ == '__main__':
__run__()

Categories

Resources