Any help on placing buttons with Tkinter in Python? - python

UPDATE - I got it to work by using the .grid() function in Tkinter. Thanks for all the help!
I would like to make a button that will center itself in the middle of the GUI in Tkinter, but I have tried using the place() function and also, the pack() function will not work. Any tips or advice?
A section of my code:
restart = Button(tk, text = "Restart", command = restartGame)
restart.pack()
#The code to place the button in the middle goes here

I rarely ever recommend using place, but if you literally only have a single widget that you want to put in the center of some other widget, place is a really good choice:
restart.place(relx=.5, rely=.5, anchor="center")
relx sets the relative x coordinate to be the middle (it is a floating point value between 0.0 and 1.0)
rely sets the relative y coordinate to be the middle
anchor specifies that the center of the widget should be at the x/y coordinate

I assume you mean centering the button at the middle of the top/bottom.
You can use .pack(side = "bottom") to place the button at the bottom (middle) of the Tk window.
Using side =, you can define it as top, bottom, left, or right.
So this means that your code would look like:
restart = Button(tk, text = "Restart", command = restartGame)
restart.pack(side = "bottom")

Related

Tkinter button default infinitely large

I am trying to set up a basic GUI with two buttons and some number of labels (maybe 4 or so).
I was under the impression that Tkinter buttons had a default size that was relative to the amount of text contained in the button. When my buttons appear on the screen however, they seem to take up as much of the screen as possible depending on where I place them. Here is my code:
from tkinter import *
root = Tk()
screen_width = root.winfo_screenwidth()
screen_height = root.winfo_screenheight()
screen_width2 = screen_width/1.3
screen_height2 = screen_height/1.3
a = str(int(screen_width2)) + "x" + str(int(screen_height2))
root.geometry (a)
root.title("Tester")
welcomeUser = Label(root, text ="Welcome User")
upload = Button(root, text="Upload")
run = Button(root, text="Run")
welcomeUser.place(bordermode=INSIDE, relheight= 0.25, relwidth= 1.0)
upload.place(bordermode=INSIDE, relheight= 1.0, relwidth= 0.25)
run.place(bordermode=INSIDE, relheight= 1.0, relwidth= 1.75)
root.mainloop()
For example, when I run this code, the text for the "run" button is in the correct place, but the actual button takes up the entire window. Whichever button is run last eclipses everything else in the window.
I tried to resize the button with config() and just by changing the size within its own parameters like run = Button(root, text="Run", height=100, width=100).
I know it has something to do with the fact that I'm using place(), because when I use pack() or grid(), the button size is default (size of text).
For the people who are going to say "Use grid instead of place()" - I can't figure out how grid() would better. It seems much less intuitive and much less effective, especially for screen resolution dependent application window sizes (as is part of my code). In fact the whole format of grid() is much weaker than just using floats measures relative to window (I.E. how is done using place). I come from an OS background where this is standard practice, and people who use pixels etc are derided. The script seems to be flipped on StackOverflow with Tkinter, though. Feel free to change my mind.
My question is, how can I can keep the buttons at their default size (encapsulating text) while still being able to place them effectively?
When you use place and specify relwith and/or relheight, you are requesting that the buttons width or height be relative to its parent. In this case the parent is the root window.
Thus, if you set the relheight to 1, you are requesting that the button be exactly as tall as the whole window. Similarly, when you set relwidth to .25, you are asking it to be 1/4 as wide as the whole window.
You can easily see this by simply removing the relwidth and relheight properties and the buttons will be their natural size.

Correct way to set scrollbar position in python tkinter

I am making a basic text editor and I am saving the scroll position in a file on closing the program. Then when opening the program it will read the scroll position from the file and update it so you can continue where you left off.
I can get the position fine from scrolledtext.yview() which returns a tuple with e.g. (0.42, 0.75)
But I cannot figure out how to change the scroll position. I have tried scrolledtext.vbar.set(0.42, 0.75) to try and update it but that doesn't work as in it doesn't do anything and gives no errors. I have also tried scrolledtext.yview(0.42, 0.75) but it says TclError: bad option "0.42": must be moveto or scroll so if anyone knows how to update it that would be greatly appreciated, cheers.
Edit(Code):
import tkinter as tk
root = tk.Tk()
Frame = frame(root)
Frame.pack()
textbox = ScrolledText(Frame)
textbox.pack()
textbox.yview() #this is saved to file, produces tuple of e.g. (0.42, 0.75)
textbox.vbar.set(0.3, 0.7) #this doesn't produce any errors but doesn't change the scroll position
textbox.yview(0.3, 0.7) #this is also something i have tried but produces the error _tkinter.TclError: bad option "0.4243827160493827": must be moveto or scroll
root.mainloop()
You can't expect the saved yview to work in all cases. If the file has been edited, the proportions could be all wrong.
The tuple you get from yview represents the fraction visible at the top and the fraction visible at the bottom. You can call yview_moveto to set the position at the top, and then let tkinter take care of the fraction at the bottom.
For example, if the yview you've saved is (0.42, 0.75), then you just need to call yview_moveto('0.42'). This will cause the view to be adjusted so that the given offset is at the top of the window.
In case of widgets update with change bbox sizes, i use a followed snippet to keep scroll position:
#before repaint store vsb position caclulated in pixels from top
bbox = canvas.bbox(ALL)
self.mem_vsb_pos = canvas.yview()[0] * (bbox[3] - bbox[1])
#after repaint (back calculation):
bbox = canvas.bbox(ALL)
canvas.yview_moveto(self.do_vsb_pos / (bbox[3]-bbox[1]))
#before repaint - if need repaint from top
self.mem_vsb_pos = 0.0

Tkinter - change location of treeview

I use tkinter for an assigment with a treeview:
tree = ttk.Treeview(root)
tree["columns"]=("one","two","three")
tree.column("one", width=100 )
tree.column("two", width=100)
tree.column("three", width=120)
tree.heading("one", text="3")
tree.heading("two", text="2")
tree.heading("three", text="1")
tree.place(x=0,y=0)
then it places it at the top left corner where it should be.
But whenever I start writing using this
tree.insert("", 0, values=(1, 2, 3))
it goes to a y axes of 0 and a x axes that is in the middle of screen.
Is there any way to fix it so that it stays on the top left corner?
To explain the query you had in the comments above.
.pack() differs from .place() when it comes to positioning of the widgets. For a start .pack()'s default position for displaying widgets is the top, middle of it's parent if it is the first widget to be default packed in the parent, else it's the middle of the bottom edge of the last widget to be default packed in the parent. Where calling .place() without any attributes will not actually draw the widget visibly on the screen, instead you must clarify a position for the widget (there are several sets of attributes which can be used for this with .place()).
This is why using .pack() on the widget instead of .place() caused it to move to the top middle of the screen.
If there are any others out there that are having troubles when you write .place and it just stays in the same location, it might be because later on in the code you have another .place referring to the same object that overrides the original placement. Just do a control + f and type in object_name.place( and see if any other lines appear.

Tkinter box issues- Entry, Labelbox, Text all take up space from side to side, grid crashes computer

I'm using a tkinter canvas and trying to make a chat box on the right side of my game. However, I found that when I do...
import turtle
import tkinter as tk
master = tk.Tk()
w = tk.Canvas(master,width=1155,height=600,cursor='cross_reverse', bg='#101010')
shift = 1.000
sc = turtle.TurtleScreen(w)
tu = turtle.RawTurtle(sc)
e = tk.Entry(master, bg = '#000', fg = '#03f', font = 'Courier', justify='right', insertbackground = '#101010',width='115')
lb = tk.Listbox(master,height=3)
#e.grid(row=3,column=3)
sc.bgcolor("#101010")
txt = tk.Text(master,state="disabled")
txt.pack()
lb.pack()
w.pack()
sc.tracer(100)
drawcontinents() #Draws stuff with turtle, works just fine
e.pack()
tk.mainloop()
... a few things go wrong.
1.Text and Entry do not seem to want to coexist. I seem to be only able to have one or the other. My plan was to use entry as a chat entry, and display messages in Text. My backup plan is to append messages to label.
2.Text, entry, and Label box take up the entire window in whatever rows they are in, which blocks out the rest of what I am trying to draw. In other words,it puts the text box in the center, with a big gray stripe from side to side across whatever I've drawn. Is there any way to just display the box, and put it to the right?
3.Whenever I try to use the grid system, my whole computer freezes and I have to restart. Is this because the program is taking up more space than I have available, or is this a known bug or problem with installation?
You cannot use both pack and grid at the same time for the same containing widget (ie: for all widgets inside the same frame, toplevel or root window).
What happens is this: grid lays out all the widgets, potentially changing the size of some widgets based on your options (ie: it may grow a widget to stick to the sides of the cell). pack then notices that some widgets changed size in the containing widget it thinks it is responsible for, so it redoes what it thinks is the proper layout. This may change the size of some widgets based on your options. grid then notices that some widgets it thinks it is responsible for change size so it redoes what it does, potentially changing the size of some widgets. pack notices and re-adjusts, grid notices and re-adjusts, pack notices, ... until the end of time.
The solution is simple: only use grid, or only use pack, for all widgets that have a common parent. In this case, all your widgets share the root window as their parent, so they all need to use grid, or they all need to use pack.

How to pack a tkinter widget underneath an existing widget that has been packed to the left side?

I'm attempting to write a basic Tkinter GUI that has a Text widget at the top, then a Button widget left aligned under it, then another Text widget underneath the button. The problem I'm having is, after packing the Button widget to the left, when I then go to pack the second Text widget, it puts it next to the button on the right, rather than underneath the button. This happens regardless of what I set the side argument to for the second Text widget Here's a simple piece of code that demonstrates this behaviour:
from Tkinter import *
root = Tk()
w = Text(root)
w.pack()
x = Button(root, text="Hi there!")
x.pack(side=LEFT)
y = Text(root)
y.pack(side=BOTTOM)
root.mainloop()
So how would I go about setting up the second Text widget so that it appears below the button, rather than to the right of it?
There are generally two solutions to layout problems:
switch to using grid. It becomes real easy to do layouts like what you are trying to accomplish. Grid can solve probably 95% of all layout issues (it's amazing when you think about it -- Tk does with one manager what most toolkits need half a dozen to accomplish!)
use multiple frames. If some widgets need to be stacked top-to-bottom and some left-to-right you can't always get what you want packing everything in a single frame. Use one frame for the top-to-bottom parts of the layout and additional frames for the left-to-right content.
Also realize that widgets don't have to be children of the widget in which they are packed/gridded. You can use the "in" parameter to put widgets in some other container than their parent.
For example, in your specific example you can create three frames, top, middle, bottom. Pack these top-to-bottom in your toplevel window. Then you can pack the first text widget in the top, the button or buttons horizontally in the middle, and the other text widget in the bottom.
The advantage to such an approach is that it makes it much easier to change the layout in the future (which in my experience always happens at some point). You don't have to re-parent any of your widgets, just pack/place/grid them in some other container.
In your short example it doesn't make much difference, but for complex apps this strategy can be a life saver.
My best advice is this: layout isn't an afterthought. Do a little planning, maybe even spend five minutes drawing on some graph paper. First decide on the major regions of your app and use a frame or some other container for each (paned window, notebook, etc). Once you have those, do the same divide-and-conquer approach for each section. This lets you use different types of layout for different sections of your app. Toolbars get horizontal layout, forms might get vertical layout, etc.
I was initially misunderstanding how packing worked and didn't realise that the entire left side was being "claimed" when i did x.pack(side=LEFT). What I found after reading this and the answer by Alex here is that I was not really after having x packed to the left side at all, but rather having it anchored to the left, using anchor=W (W for West) instead of side=LEFT. My revised code snippet which does what I was after looks like this:
from tkinter import *
root = Tk()
w = Text(root)
w.pack()
x = Button(root, text="Hi there!")
x.pack(anchor=W)
y = Text(root)
y.pack(side=BOTTOM)
root.mainloop()
This way x is not "claiming" the left side anymore, it's just aligned to the left (or West) within its block of space.
Packing happens in the order the .pack methods are called, so once x has "claimed" the left side, that's it -- it will take up the left portion of its parent and everything else within its parent will be to its right. You need a Frame to "mediate", e.g....:
from Tkinter import *
root = Tk()
w = Button(root, text="Mysterious W")
w.pack()
f = Frame(root)
x = Button(f, text="Hi there!")
x.pack()
y = Button(f, text="I be Y")
y.pack(side=BOTTOM)
f.pack(side=LEFT)
root.mainloop()
(changed Texts to Buttons for more immediate visibility of layout only -- the Tkinter on this Mac doesn't show Texts clearly until they have focus, but Buttons are quite clear;-).
Do it the same way that WebView does using the Mosaic Canvas Widget Sets internals(which are very similar to Tk). The trick is that the second identical named Frame Object works as a Block Level Float(inline:block;) for everything placed after it and everything that calls "fr" already will automatically begin over inside of it.
You can have many doing this of TOP aligned widgets and simply add another identical named Frame where you want to break between side=LEFT's. Works after Bottom also.
fr=Frame(root)
fr.pack(fill=X, side=TOP)
block1=Label(fr)
block1.pack(side=LEFT)
block2=Label(fr)
block2.pack(side=LEFT)
block3=Button(fr)
block3.pack(side=LEFT)
# NAME IT THE SAME ID NAME AS THE FIRST MAIN FRAME...
fr=Frame(root)
fr.pack(fill=X, side=TOP)
# These NOW jump into the second Frame breaking the side=LEFT in new Frame
block4=Label(fr)
block4.pack(side=LEFT)
block5=Label(fr)
block5.pack(side=LEFT)
# AND THEY CONTINUE GOING side=LEFT AFTERWARDS.

Categories

Resources