How to change the button position when pressed in tkinter python - python-3.x

please tell me how to change the position of the button in tkinter. I predicted that it could be done by button['padx' = 4], but it doesn't work. Do you know how to do it?
from tkinter import ttk
import random
window = tk.Tk()
window.geometry('512x512')
def click():
pass
button = ttk.Button(
text="No",
command=click
).pack(padx=5, pady=15)
window.mainloop()

I instead assigned 2 variables to random integers, and then updated the position of the button with those variables. If you want the random position to be a wider area increase the number "100" in "random_int".
from tkinter import *
import random
window = Tk()
window.geometry('512x512')
x = 5
y = 15
def click():
random_int = random.randint(0, 100)
x = (random_int)
random_int = random.randint(0, 100)
y = (random_int)
button.place(x=x, y=y)
button = Button(text="No", command=click)
button.pack(padx=5, pady=15)
window.mainloop()

Related

How to insert a loop function into a label in Tkinter (self_updatable)

I have this loop that runs and changes x, how should I put it into a Tkinter label? Thanks in advance.
from tkinter import *
import time
root = Tk()
def x_loop():
x = 0
while x <= 100:
time.sleep(2)
x = x + 1
l = Label(root, text = x_loop).pack(pady = 20)
root.mainloop()
Tkinter dosent like while loops, this is because a while loop dosent return to the mainloop till its finished and therefore you application isnt working during this time.
Tkinter provides for this the .after(*ms,*func) method and is used below.
Also for changing the text of a tk.Label you can go for several ways. I think the best way is to use the inherated option textvariable.
The textvariable needs to be a tk.*Variable and configures the tk.Label as soon as the var is set.
Check out the working example below:
import tkinter as tk
x = 0
def change_text():
global x
var.set(x)
x +=1
root.after(100,change_text)#instead of a while loop that block the mainloop
root = tk.Tk()
var = tk.StringVar()
lab = tk.Label(root, textvariable=var)
lab.pack()
change_text()
root.mainloop()
Instead of using StringVar as #Atlas435 did, you can use this simpler method:
import tkinter as tk
def x_loop():
global x
if x <= 100:
x += 1
# Update the label
label.config(text=x)
# after 2000 ms call `x_loop` again
root.after(2000, x_loop)
x = 0
root = tk.Tk()
label = tk.Label(root, text=x)
label.pack(pady=20)
# STart the loop
x_loop()
root.mainloop()

Tkinter display class list text

I have the following piece of code: I am trying to get the text from function showText to actually appear in the window
from tkinter import *
import wikipedia
from nltk.tokenize import sent_tokenize, word_tokenize
import time
subject = wikipedia.page("Assembly language")
#print(p.url)
#print(p.title)
plain_text = subject.content
plain_text_words = word_tokenize(plain_text)
class Window(Frame):
def __init__(self, master= None):
Frame.__init__(self, master)
self.master = master
self.init_window()
def init_window(self):
self.master.title('Test')
self.pack(fill=BOTH, expand =1)
quitButton = Button(self, text = 'Exit', command=self.client_exit)
quitButton.place(x=500, y=300)
menu = Menu(self.master)
self.master.config(menu=menu)
file = Menu(menu)
menu.add_cascade(label='File', menu=file)
file.add_command(label='Run', command=self.showText)
file.add_command(label='Exit', command=self.client_exit)
help_menu = Menu(menu)
menu.add_cascade(label='Help', menu=help_menu)
help_menu.add_command(label='About')
def showText(self):
for i in range (0, len(plain_text_words)):
words = [i]
time.sleep(3)
words.pack()
def client_exit(self):
exit()
root = Tk()
w = 600 # width of the window
h = 370 # height of the window
# get screen width and height
ws = root.winfo_screenwidth()
hs = root.winfo_screenheight()
# calculate x and y coordinates for the Tk root window
x = (ws/2) - (w/2)
y = (hs/2) - (h/2)
root.geometry('%dx%d+%d+%d' % (w, h, x, y))
The piece that's causing me grief is this bit:
def showText(self):
for i in range (0, len(plain_text_words)):
words = [i]
time.sleep(3)
words.pack()
I am trying to get each piece of text to show as individual words on the window but no matter how I try and do it, I get an error. I have tried various things such as converting to lists etc Hoping someone can help..
PS: You will need to download the nltk dataset before this code will run
First of all, your pack function misses the brackets.
Second, your var words is a list. Not a tkinter widget. You can only pack tkinter widgets.
To solve it you need to add the list to a text widget for example.

Trouble filling a Python tkinter/turtle window with squares

I'm having trouble with getting the turtle.begin_fill() / turtle.end_fill() commands to work in a tkinter window. I want to have the program draw a bunch of coloured cells onto the screen in a 64x32 grid. This the whole code to set up the window and draw however it simply doesn't do anything after setting up a window:
import turtle as tu
import tkinter as tk
axis = []
num = -512
for i in range(0,64):
axis.append(num)
num = num + 16
def drawworld(*args):
for i in range(0,64):
for j in range(0,32):
tu.goto(axis[i],axis[j]+256)
tu.pd()
tu.color=("#ffff00")
tu.begin_fill()
for k in range(0,4):
tu.fd(16)
tu.lt(90)
tu.end_fill()
tu.pu()
root = tk.Tk()
root.title("game")
root.resizable(False, False)
canvas = tk.Canvas(master = root, width = 1024, height = 512)
canvas.grid(row=0, column=0, columnspan=10)
tu = tu.RawTurtle(canvas)
tu.speed(50)
tu.pu()
tu.ht()
drawworld()
root.mainloop()
however, if I were to comment out the fill lines, the code works perfectly (without colouring the boxes) which means there must be something wrong with:
tu.color=("#ffff00")
tu.begin_fill()
for k in range(0,4):
tu.fd(16)
tu.lt(90)
tu.end_fill()
tu.pu()
I've looked up the documentation and this should be perfect syntax. What am I doing wrong?
I believe your problem is this line:
tu.color=("#ffff00")
which probably should be:
tu.color("#ffff00")
to set the color, you don't assign to the turtle's color property but rather invoke the turtle's .color() method. Your code with this change and some other cleanup:
import tkinter as tk
from turtle import RawTurtle
axis = []
num = -512
for _ in range(64):
axis.append(num)
num += 16
def drawworld():
for i in range(64):
for j in range(32):
tu.goto(axis[i], axis[j] + 256)
tu.pendown()
tu.color("#ffff00")
tu.begin_fill()
for _ in range(4):
tu.forward(16)
tu.left(90)
tu.end_fill()
tu.penup()
root = tk.Tk()
root.title("game")
root.resizable(False, False)
canvas = tk.Canvas(master=root, width=1024, height=512)
canvas.grid(row=0, column=0, columnspan=10)
tu = RawTurtle(canvas)
tu.speed('fastest')
tu.hideturtle()
tu.penup()
drawworld()
root.mainloop()
However, this is a painfully slow way to go about this. There are faster ways, here's one that uses stamping to speed up the process:
import tkinter as tk
from turtle import RawTurtle
from random import random
CUBE_SIZE = 16
CURSOR_SIZE = 20
WIDTH, HEIGHT = 1024, 512
axis = []
num = -HEIGHT
for _ in range(WIDTH // CUBE_SIZE):
axis.append(num)
num += CUBE_SIZE
def drawworld():
for i in range(WIDTH // CUBE_SIZE):
tu.goto(axis[i] + CUBE_SIZE // 2, axis[0] + HEIGHT // 2 + CUBE_SIZE // 2)
for j in range(HEIGHT // CUBE_SIZE):
tu.color(random(), random(), random())
tu.stamp()
tu.forward(CUBE_SIZE)
root = tk.Tk()
root.title("game")
root.resizable(False, False)
canvas = tk.Canvas(master=root, width=WIDTH, height=HEIGHT)
canvas.grid(row=0, column=0, columnspan=10)
tu = RawTurtle(canvas)
tu.shape('square')
tu.shapesize(CUBE_SIZE / CURSOR_SIZE)
tu.speed('fastest')
tu.hideturtle()
tu.setheading(90)
tu.penup()
drawworld()
root.mainloop()

Generate 10 balls in tkinter canvas

Ok guys.
I am trying to generate 10 balls of random color in Tkinter canvas when I click the generate button.
Program works, and random color choice works for the ball, but I only get one ball generated at a time.
Every time I click the button it randomly moves the ball around, but all I want is 10 balls in 10 random positions at a time. I am using Python 3.4 on a Linux box.
This is a code I've got:
from tkinter import *
import random # to generate random balls
colors = ["red", "blue", "purple", "green", "violet", "black"]
class RandomBalls:
"""
Boilerplate code for window in Tkinter
window = Tk()
window.title("Random title")
window.mainloop()
"""
def __init__(self):
"""
Initialize the window and add two frames, one with button, and another one with
canvas
:return:
"""
window = Tk()
window.title("Random balls")
# A canvas frame
frame1 = Frame(window)
frame1.pack()
self.canvas = Canvas(frame1, width = 200, height = 300, bg = "white")
self.canvas.pack()
# A button frame
frame2 = Frame(window)
frame2.pack()
displayBtn = Button(frame2, text = "Display", command = self.display)
displayBtn.pack()
window.mainloop()
def display(self):
for i in range(0, 10):
self.canvas.delete("circle") # delete references to the old circle
self.x1 = random.randrange(150)
self.y1 = random.randrange(200)
self.x2 = self.x1 + 5
self.y2 = self.y1 + 5
self.coords = self.x1, self.y1, self.x2, self.y2
self.canvas.create_oval(self.coords, fill = random.choice(colors), tags = "circle")
self.canvas.update()
RandomBalls()
Every time through your loop you are deleting everything you created before, including what you created the previous iteration. Move the delete statement outside of the loop:
def display(self):
self.canvas.delete("circle")
for i in range(0, 10):
...

tkinter messagebox link to notebook page

referwork = ttk.Notebook(root, style =".TNotebook")
f1 = ttk.Frame(referwork)
f2 = ttk.Frame(referwork)
referwork.add(f1, text="Search", padding = 1)
referwork.add(f2, text="Add/Delete", padding = 1)
#referwork.configure (height = 500, width = 800)
referwork.grid(row=0, column=0, sticky=(N,W,S,E))
I have used the above to create a two-tab notebook. On the first a search is performed. What I want to do is to have an alert in a message box appear messagebox.askyesno and when 'yes' is selected that the focus moves to the second page of the notebook
messagebox.askyesno(0.0,'"{0}"{1} \n {2}\n'.format(search_analyte.get(),' is not in the database.','Add,if appropriate'))
if True:
is as far as I have got. I cannot figure out how to 'open' the second page using this dialogue and conditional. Many thanks for any help
Use Notebook.select(tab) method, where tab is one of the notebook child widgets.
from tkinter import *
from tkinter.ttk import *
from tkinter.messagebox import askyesno
def open_first():
referwork.select(f1)
def open_second():
if askyesno('Title', 'Press "Yes" to open second page') == YES:
referwork.select(f2)
root = Tk()
referwork = Notebook(root, style =".TNotebook")
f1 = Frame(referwork)
f2 = Frame(referwork)
Button(f1, text='Go =>', command=open_second).pack(padx=100, pady=100)
Button(f2, text='<= Go', command=open_first).pack(padx=100, pady=100)
referwork.add(f1, text="Search", padding = 1)
referwork.add(f2, text="Add/Delete", padding = 1)
referwork.grid(row=0, column=0, sticky=(N,W,S,E))
root.mainloop()

Resources