import tkinter as tk
from tkinter import *
HEIGHT = 600
WIDTH = 600
root = tk.Tk()
def button_event1():
import ThreePlayers
print(ThreePlayers)
def button_event2():
import TwoPlayersGame
print(TwoPlayersGame)
def button_event3():
print("")
def button_event4():
print("")
def button_event5():
quit()
root = Tk()
root.title('Connect 4 Game')
canvas = tk.Canvas(root, height=HEIGHT, width=WIDTH)
canvas.pack()
L = Label(root, text="Welcome to 3P Connect 4!!!",font=("Ariel",20,"bold", "underline"))
L.config(anchor=CENTER)
L.pack()
button = tk.Button(root, text="3 Player Game", command=button_event1)
button.pack()
button = tk.Button(root, text="2 Player Game", command=button_event2)
button.pack()
button = tk.Button(root, text="1 Player Game", command=button_event3)
button.pack()
button = tk.Button(root, text="Options", command=button_event4)
button.pack()
button = tk.Button(root, text="QUIT", command=button_event5)
button.pack()
root.mainloop()
Above is my Code for a Tkinter GUI but I want the have the label at the center of the root/window how do I do that? Currently its sitting on top of the buttons everything else is fine the button events and such works
In my opinion, you should have used place or grid instead of pack. Because pack only gives few alignment options.
otherwise, maybe divide the main window into two frames then pack the label at the top of the lower frame
frame = Frame(root)
frame.pack()
bottomframe = Frame(root)
bottomframe.pack( side = BOTTOM )
L = Label(root, text="Welcome to 3P Connect 4!!!",font=("Ariel",20,"bold", "underline"))
L.pack(side = TOP)
I wish this helps. but you should use grid for better alignment or place.
You can use the following commands to place the label in the center
L = Label(root, text="Welcome to 3P Connect 4!!!",font=("Ariel",20,"bold", "underline"))
# L.config(anchor=CENTER)
# L.pack()
L.place(x=HEIGHT/2, y=WIDTH/2, anchor="center")
Similarly, you can also use button.place(x=100, y=25) for buttons
REF: Tkinter: Center label in frame of fixed size?
Related
I'm working on Tkinter window, and I want to set up the height and width of the screen without the geometry function, so I made 2 scales vertical and horizontal, then I use a button with a command that set up the window size in the following code:
root = Tk()
root.title("Root window")
label = Label(root, text="The height").pack()
slay = Scale(root, from_=0, to=200)
slay.pack()
my_label = Label(root, text="The width").pack()
hor = Scale(root, from_=0, to=250, orient=HORIZONTAL)
hor.pack()
def btns():
root.geometry(str(f"{slay.get} x {hor.get}"))
btn = Button(root, text="Setup the window size", command=btns).pack()
And the error is:
line 20, in btns
root.geometry(str(f"{slay.get} x {hor.get}"))
You are just referencing the .get() function, never actually calling them. So you will receive an error.
Call the function using (). Also, there is no space between str(f"{slay.get()} x {hor.get()}").
So it would look something like this:
root.geometry(str(f"{slay.get()}x{hor.get()}"))
This works.
The problem was root.geometry(str(f"{vert.get} x {hori.get}"))
I changed it to this root.geometry(str(f"{vert.get()}x{hori.get()}"))
Simply removed the spaces around 'x' and added () to the get
Also added orient = VERTICAL to slay
root = Tk()
root.title("Root window")
label = Label(root, text="The height").pack()
slay = Scale(root, from_=0, to=200, orient=VERTICAL)
slay.pack()
my_label = Label(root, text="The width").pack()
hor = Scale(root, from_=0, to=250, orient=HORIZONTAL)
hor.pack()
def btns():
print( slay.get(), hor.get() )
root.geometry(str(f"{slay.get()}x{hor.get()}"))
btn = Button(root, text="Setup the window size", command=btns).pack()
root.mainloop()
I'm trying to use tkinter's buttons to control a turtle in another graphics window, but the buttons don't function
I was trying to use turtle graphics and Tkinter to make a simple program that controls a turtle with buttons. However, it seems that only one button is actually running a function, and even that is producing an error. Here is the code I wrote:
from tkinter import *
import turtle
global x
global y
x = 1
y = 1
i = 0
root = Tk()
wn = turtle.Screen()
bob = turtle.Turtle()
bob.up()
def goUp(event):
y=y+5
bob.goto(x,y)
def goDown(event):
y=y-5
bob.goto(x,y)
def goRight(event):
x=x+5
bob.goto(x,y)
def goLeft(event):
x=x-5
bob.goto(x,y)
topFrame = Frame(root)
topFrame.pack()
middleFrame = Frame(root)
middleFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack()
button1 = Button(topFrame, text = "Up", fg="red")
button2 = Button(middleFrame, text = "Left", fg="red")
button3 = Button(middleFrame, text = "Right", fg="red")
button4 = Button(bottomFrame, text = "Down", fg="red")
button1.bind("<Button-1>", goUp)
button2.bind("<Button-2>", goLeft)
button3.bind("<Button-3>", goRight)
button4.bind("<Button-4>", goDown)
button1.pack()
button2.pack(side=LEFT)
button3.pack(side=RIGHT)
button4.pack()
root.mainloop()
The TKinter Button class accepts a command option where you can pass in the function that gets called when a button is pressed. You also need to access the global x and y variables inside your methods.
Try this code:
from tkinter import *
import turtle
global x
global y
x = 1
y = 1
i = 0
root = Tk()
wn = turtle.Screen()
bob = turtle.Turtle()
bob.up()
def goUp():
global x, y
y=y+5
bob.goto(x,y)
def goDown():
global x, y
y=y-5
bob.goto(x,y)
def goRight():
global x, y
x=x+5
bob.goto(x,y)
def goLeft():
global x, y
x=x-5
bob.goto(x,y)
topFrame = Frame(root)
topFrame.pack()
middleFrame = Frame(root)
middleFrame.pack()
bottomFrame = Frame(root)
bottomFrame.pack()
button1 = Button(topFrame, text = "Up", fg="red", command=goUp)
button2 = Button(middleFrame, text = "Left", fg="red", command=goLeft)
button3 = Button(middleFrame, text = "Right", fg="red", command=goRight)
button4 = Button(bottomFrame, text = "Down", fg="red", command=goDown)
button1.pack()
button2.pack(side=LEFT)
button3.pack(side=RIGHT)
button4.pack()
root.mainloop()
Turtle's Turtle and Screen classes are generally used when turtle.py is used standalone. When turtle, which is implemented atop tkinter, is used embedded inside tkinter, we generally use the RawTurtle and TurtleScreen classes instead. You'll find more about this in the turtle documentation
You also should review one of the many online Python global keyword tutorials as you're not using it correctly. Fortunately, we don't need it to implement this particular program.
Here's a rework of your code, as a single window implementation, that illustrates the above:
import tkinter as tk
from turtle import RawTurtle, TurtleScreen
def goUp():
bob.sety(bob.ycor() + 5)
def goDown():
bob.sety(bob.ycor() - 5)
def goRight():
bob.setx(bob.xcor() + 5)
def goLeft():
bob.setx(bob.xcor() - 5)
root = tk.Tk()
canvas = tk.Canvas(root, width=500, height=500)
canvas.pack()
wn = TurtleScreen(canvas)
bob = RawTurtle(wn, shape="turtle")
bob.penup()
topFrame = tk.Frame(root)
topFrame.pack()
middleFrame = tk.Frame(root)
middleFrame.pack()
bottomFrame = tk.Frame(root)
bottomFrame.pack()
tk.Button(topFrame, text="Up", fg="red", command=goUp).pack()
tk.Button(middleFrame, text="Left", fg="red", command=goLeft).pack(side=tk.LEFT)
tk.Button(middleFrame, text="Right", fg="red", command=goRight).pack(side=tk.RIGHT)
tk.Button(bottomFrame, text="Down", fg="red", command=goDown).pack()
wn.mainloop()
I am trying to create the buttons using tkinter.
Here is my code
import tkinter as tk
def pressed():
print("button pressed!")
def create_layout(frame):
frame.pack(fill=None,expand=True)
mycolor = '#%02x%02x%02x' % (250, 250, 210)
root.configure(bg=mycolor)
bottomframe = tk.Frame(root)
bottomframe.pack( side = tk.LEFT )
button1 = tk.Button(frame, text="Button1", fg="black",command=pressed,anchor="w")
button1.pack( side = tk.LEFT)
button2 =tk.Button(frame, text="Button2", fg="black",command=pressed,anchor="w")
button2.pack( side = tk.LEFT )
root = tk.Tk()
root.geometry("250x150")
frame = tk.Frame(root)
create_layout(frame)
root.mainloop()
I have specified the anchor="w", and side="LEFT", but it does not seem to be work.
Output of the code:
Changing frame.pack(fill=None,expand=True) to frame.pack(fill=None,expand=True, anchor="w") will align the buttons to the left side.
I am a python self learner. I was stuck on some practice.
My idea was to create a pop out GUI with buttons that can change the canvas colour.
from Tkinter import *
import ttk
import tkMessageBox
root = Tk()
root.title("Colour!")
canvasColor = "yellow"
def buttonRed() :
canvas = Canvas(root, bg = "red", height=100, width=100)
canvas.grid(row=0,column=2)
button = ttk.Button(root, text="Red", command = buttonRed)
button.grid(row=2,column=1)
button2 = ttk.Button(root, text ="Green", command = buttonGreen)
button2.grid(row=2,column=2)
button3 = ttk.Button(root, text="Blue", command = buttonBlue)
button3.grid(row=2,column=3)
canvas = Canvas(root, bg = canvasColor, height=200, width=200)
canvas.grid(row=0,column=2)
root.configure(background='white')
root.mainloop()
i haven't put in the green and blue button command yet, but instead of creating a new canvas when the colour button clicked, i just wanted to have the default canvas colour change.
Any help will be much appreciated!
Thanks in advance.
I think this is what you need -
from Tkinter import *
import ttk
import tkMessageBox
root = Tk()
root.title("Colour!")
canvasColor = "yellow"
def buttonRed() :
canvas.config(background="red")
def buttonGreen() :
canvas.config(background="green")
def buttonBlue() :
canvas.config(background="blue")
button = ttk.Button(root, text="Red", command = buttonRed)
button.grid(row=2,column=1)
button2 = ttk.Button(root, text ="Green", command = buttonGreen)
button2.grid(row=2,column=2)
button3 = ttk.Button(root, text="Blue", command = buttonBlue)
button3.grid(row=2,column=3)
canvas = Canvas(root, bg = canvasColor, height=200, width=200)
canvas.grid(row=0,column=2)
#canvas.config(background="black")
root.configure(background='white')
root.mainloop()
I am trying to center some text on a canvas, during program initialization. However, winfo_width/height don't return the correct values for me in this case, so I cannot properly place text using Canvas method create_text(), since I cannot calculate the correct center position. I can only get the correct dimensions post-init, say if I query the size in a button callback.
How to solve this? Here's the code:
try:
from Tkinter import *
except ImportError:
from tkinter import *
class GUI:
def __init__(self):
# root window of the whole program
self.root = Tk()
self.root.minsize(800, 600)
# canvas/viewport for displaying the image and drawing vectors on it
self.viewport = Canvas(self.root, bd=2, relief='ridge', highlightthickness=0)
# define master buttons for audio preview, render to file and clear all vectors
btn_preview = Button(self.root, text='Preview', command=self.Preview)
# layout managing
self.viewport.grid(columnspan=3, padx=5, pady=5, sticky=N+S+W+E)
btn_preview.grid(row=1, padx=85, pady=10, ipadx=5, ipady=5, sticky=W)
# position text on canvas to notify user he can load the image by clicking it
self.viewport.update_idletasks()
textpos = (self.viewport.winfo_width(),self.viewport.winfo_height())
print(textpos)
self.viewport.create_text(textpos[0] / 2, textpos[1] / 2, text="Click here to load an image!", justify='center', font='arial 20 bold')
# weights of rows and columns
self.root.rowconfigure(0, weight=1)
self.root.columnconfigure(0, weight=1)
def Preview(self, event=None):
textpos = (self.viewport.winfo_width(),self.viewport.winfo_height())
print(textpos)
if __name__ == '__main__':
mainwindow = GUI()
mainloop()
Compare the dimensions returned on init to dimensions after you click the Preview button. They're different!
OK haha, I managed to solve it after checking this answer. I needed to bind <Configure> event to the canvas, and define a function that does stuff when window is resized. It's working now!
try:
from Tkinter import *
except ImportError:
from tkinter import *
class GUI:
textid = 0
def __init__(self):
# root window of the whole program
self.root = Tk()
self.root.minsize(800, 600)
# canvas/viewport for displaying the image and drawing vectors on it
self.viewport = Canvas(self.root, bd=2, relief='ridge', highlightthickness=0)
# define master buttons for audio preview, render to file and clear all vectors
btn_preview = Button(self.root, text='Preview', command=self.Preview)
# layout managing
self.viewport.grid(columnspan=3, padx=5, pady=5, sticky=N+S+W+E)
btn_preview.grid(row=1, padx=85, pady=10, ipadx=5, ipady=5, sticky=W)
# weights of rows and columns
self.root.rowconfigure(0, weight=1)
self.root.columnconfigure(0, weight=1)
# bind mouse actions for the canvas
self.viewport.bind('<Configure>', self.ResizeCanvas)
def Preview(self, event=None):
textpos = (self.viewport.winfo_width(),self.viewport.winfo_height())
print(textpos)
def ResizeCanvas(self, event):
if self.textid != 0:
event.widget.delete('openfiletext')
# position text on canvas to notify user he can load the image by clicking it
textpos = (self.viewport.winfo_width(), self.viewport.winfo_height())
self.textid = self.viewport.create_text(textpos[0] / 2, textpos[1] / 2, text="Click here to load an image!", justify='center', font='arial 20 bold', tag='openfiletext')
if __name__ == '__main__':
mainwindow = GUI()
mainloop()