Python 3.4.0.
Could you help me understand what is going on here:
from tkinter import *
root = Tk()
f = Frame(root, borderwidth=2) #
for relief in [RAISED, SUNKEN, FLAT, RIDGE, GROOVE, SOLID]:
Label(f, text=relief, width=10, relief = relief).pack(side=LEFT) #
#f = Frame(root, borderwidth=2, relief = relief)
#Label(f, text=relief, width=10).pack(side=LEFT)
f.pack(side=LEFT, padx=5, pady=5)
root.mainloop()
If I uncomment now commented lines and comment the lines that hafe '#' mark at the end, the result is the same.
First case: the present situation. It is understandable to me. Before the loop we create a frame. Then pack method places each label in the parent widget (which is f). In this case f expands and contains several labels.
Well, the second case: if I switch the comment marks.
A frame f is always new. Label is also always new. A label is always placed on a separate frame. I would suggest that 5 frames would be displayed with a different label in each frame.
Could you help me understand why the result is the same?
Sounds like you want five separate windows, each of which can be moved, closed, etc.
If so, you should use the Toplevel widget instead of Frame.
from tkinter import *
root = Tk()
for relief in [RAISED, SUNKEN, FLAT, RIDGE, GROOVE, SOLID]:
t = Toplevel(root, borderwidth=2, relief = relief)
Label(t, text=relief, width=10).pack(side=LEFT)
root.mainloop()
Related
I am trying to open a toplevel window with a label from a function call but the label is not showing. What am I doing wrong?
Gratias.
from tkinter import *
import tkinter.font as fonte
def open_top():
top = Toplevel(master)
top.geometry("375x238+789+479")
top.resizable(width=FALSE, height=FALSE)
topFont = fonte.Font(family='Ubuntu', size=40)
label = Label(top, text='world', borderwidth=2, relief="sunk", width=24)
label.config(font = topFont, height=11, wraplength=350)
label.grid(row = 0, column = 0, columnspan=1, rowspan=1, sticky=W+E+N+S)
master.update()
# creating main tkinter window
master = Tk()
master.geometry("374x340+790+100")
master.resizable(width=FALSE, height=FALSE)
myFont = fonte.Font(family='Monospace', size=25)
view = Label(master, text='helo', borderwidth=2, relief="sunk", width=10)
view.config(font = ('Monospace', 36), height=3)
view.grid(row = 4, column = 0, columnspan=2, rowspan=1, sticky=W+E+N+S, padx=5, pady=5)
btn = Button(master, text ='toplevel', command = lambda: open_top())
btn.grid(row=6, column=0, columnspan=1, pady=4, padx=4)
btn = Button(master, text='Quit', command=master.destroy)
btn.grid(row=6, column=1, columnspan=1, pady=4, padx=4)
mainloop()
First about the problem:
When you create the label, you specify the width (and later) height arguments. Since your label contains text the units you pass as values to those arguments represent characters for width and lines for height (You can read about those attributes here)
#TheLizzard mention: wraplength's value also is in characters, and since you have set it to 350 and your font is not that small, it will wrap the text when a huge part of it is out of the window (and quite possibly even out of the screen) so with the current value it is quite useless. (it is also quite useless if you add static text because then you can simply add a newline or sth, a use case would be when you don't know how long the text is, for example, it was taken from user input)
Possible fixes:
Remove the width and height arguments (really the easiest):
label = Label(top, text='world', borderwidth=2, relief="sunk")
label.config(font=topFont, wraplength=350)
The widget can be also configured all at once, you don't need to use its method like this for initialization:
label = Label(top, text='world', borderwidth=2, relief="sunk", font=topFont, wraplength=350)
Change the height and width values (width tho really doesn't have to be used, especially if you use the wraplength argument):
label = Label(top, text='world', borderwidth=2, relief="sunk", font=topFont, wraplength=350, height=1)
Use anchor (really not that much of a fix or anything but will allow you to see the text (to an extent)):
label.config(anchor='nw')
Few other things:
Important (suggestions)
I strongly advise against using wildcard (*) when importing something, You should either import what You need, e.g. from module import Class1, func_1, var_2 and so on or import the whole module: import module then You can also use an alias: import module as md or sth like that, the point is that don't import everything unless You actually know what You are doing; name clashes are the issue.
Also: I strongly suggest following PEP 8 - Style Guide for Python Code. Function and variable names should be in snake_case, class names in CapitalCase. Don't have space around = if it is used as a part of keyword argument (func(arg='value')) but use if it is used for assigning a value (variable = 'some value'). Have two blank lines around function and class declarations.
I've been creating an app where there are Clients that I can add to a table, the problem is, I need a scrollbar to scroll through all the clients since the app Height is limited and the clients aren't.
Using tkinter I found a way to create a "table" using Entry and grid, but what if I want to create 100 rows? they would be outside of the view, so that's why the need of a scrollbar.
For those of you who know Java, I wanted to create something similar to Jtable, it has a method to create row, delete row, and it generates automatically that scrollbar as soon as the JTable runs out of space.
I've tried to use TkTable from ttk and mess around with some properties, but I preferred how Entries look.
root = Tk()
root.geometry("1200x900")
for i in range(10):
e = Entry(relief=RIDGE)
e.grid(row=i, column=2, sticky=N)
root.mainloop()
I created a root = Tk() and used root to grid them.
You'll see 10 Entries on top of the other.
When a window contains many widgets, they might not all be visible. However, neither a window (Tk or Toplevel instance) nor a Entry are scrollable.
One solution to make the window content scrollable is to put all the widgets in a Frame, and then, embed this Frame in a Canvas using the create_window method.
from tkinter import *
root = Tk()
canvas = Canvas(root)
scroll_y = Scrollbar(root, orient="vertical", command=canvas.yview)
frame = Frame(canvas)
# group of widgets
for i in range(100):
e = Entry(frame, relief=RIDGE, width = 100)
e.grid(row=i, column=2, sticky=N)
# put the frame in the canvas
canvas.create_window(0, 0, anchor='nw', window=frame)
# make sure everything is displayed before configuring the scrollregion
canvas.update_idletasks()
canvas.configure(scrollregion=canvas.bbox('all'),
yscrollcommand=scroll_y.set)
canvas.pack(fill='both', expand=True, side='left')
scroll_y.pack(fill='y', side='right')
root.mainloop()
output:
I am currently coding a program with will tie in with Discord's rich presence, and I am needing to create a GUI for it in Tkinter. The issue is, I cannot understand how to place elements correctly. It has been quite a pain. Here is what I am planning to have the app sort of look like: https://i.stack.imgur.com/K9Wox.jpg
However, with my current code, this is how abismal the GUI looks... https://i.stack.imgur.com/wGA9A.jpg
Here is my code:
root = tkinter.Tk()
root.title("Matter: A Discord Rich Presence Tool")
root.config(bg='#2C2F33')
root.geometry("560x300")
#root.overrideredirect(1)
# Load images
loadProfileImage = tkinter.PhotoImage(file="resources/loadprofile.png")
saveProfileImage = tkinter.PhotoImage(file="resources/saveprofile.png")
newProfileImage = tkinter.PhotoImage(file="resources/newprofile.png")
# GUI Hell starts here
topCanvas = tkinter.Canvas(root, width=600, height=150)
topCanvas.config(bd=0, highlightthickness=0, relief='ridge', background="#7289DA")
topTextFieldText = tkinter.StringVar(value='Sample top text')
topTextField = tkinter.Entry(root, textvariable=topTextFieldText)
topTextField.config(borderwidth=0, background="#7289DA")
bottomTextFieldText = tkinter.StringVar(value='Sample bottom text')
bottomTextField = tkinter.Entry(root, textvariable=bottomTextFieldText)
bottomTextField.config(borderwidth=0, background="#7289DA")
largeIconName = tkinter.StringVar()
largeIconNameField = tkinter.Entry(root, textvariable=largeIconName)
smallIconName = tkinter.StringVar()
smallIconNameField = tkinter.Entry(root, textvariable=smallIconName)
applicationIDFieldText = tkinter.StringVar()
applicationIDField = tkinter.Entry(root, textvariable=applicationIDFieldText)
applicationIDField.config(borderwidth=0, background="#23272A")
largeIconHoverText = tkinter.StringVar()
largeIconHoverTextField = tkinter.Entry(root, textvariable=largeIconHoverText)
largeIconHoverTextField.config(borderwidth=0, background="#23272A")
smallIconHoverText = tkinter.StringVar()
smallIconHoverTextField = tkinter.Entry(root, textvariable=smallIconHoverText)
smallIconHoverTextField.config(borderwidth=0, background="#23272A")
#greet_button = tkinter.Button(root, text="Run", command=run)
buttonFrame = tkinter.Frame(height=2, bd=0, relief=tkinter.SUNKEN)
newProfileButton = tkinter.Button(root, text="Save to profile", command=save)
newProfileButton.config(image=newProfileImage, borderwidth=0, background="#23272A")
saveButton = tkinter.Button(root, text="Save to profile", command=save)
saveButton.config(image=saveProfileImage, borderwidth=0, background="#23272A")
loadButton = tkinter.Button(root, command=load)
loadButton.config(image=loadProfileImage, borderwidth=0, background="#23272A")
# Grid stuff
topCanvas.grid(row=0, column=1)
applicationIDField.grid(row=3, column=1)
largeIconHoverTextField.grid(row=3, column=2)
smallIconHoverTextField.grid(row=3, column=3)
newProfileButton.grid(row=5, column=1, padx=(20, 5))
saveButton.grid(row=5, column=2, padx=(5, 5))
loadButton.grid(row=5, column=3, padx=(5, 20))
root.mainloop()
Any guidance would be greatly appreciated since I cannot seem to be able to figure out how to use Tkinter's grid to make a layout similar to the images above.
Do not try to put everything into a single grid. Divide your UI up into sections, and then use the right tool for each section.
Start at the root window
I see two major sections to your UI: a top section in blue that has some information, and a bottom section with a black background that has some buttons.
So, I would start by creating those two sections in the root window, and use pack to place one on top of the other:
topFrame = tk.Frame(root, background="#7289DA")
bottomFrame = tk.Frame(root, background="#2C2F33")
topFrame.pack(side="top", fill="both", expand=True)
bottomFrame.pack(side="bottom", fill="both", expand=True)
With that, you will now always have the root divided into two colored regions. The above code gives them an equal size. You may one to change the expand value to False for one or the other, depending on what you want to happen when the user resizes the window.
Don't worry too much about the size, though. It will change once you start adding widgets to each section.
Next, do the bottom section
The bottom also appears to be in two sections: one for inputs and one for buttons. You could use a single grid layout for this whole section, but to illustrate the concept of dividing the UI into sections we'll split the bottom into two. Plus, because everything isn't neatly lined up into rows and columns, this will make things a bit easier.
As I mentioned earlier, you may want to fiddle around with the expand option, depending on if you want these frames to resize equally or stay the same size when the user resizes the window.
inputFrame = tk.Frame(bottomFrame, background="#2C2F33")
buttonFrame = tk.Frame(bottomFrame, background="#2C2F33")
inputFrame.pack(side="top", fill="both", expand=True)
buttonFrame.pack(side="top", fill="both", expand=True)
Note: if you stop right here and try to run your program, you might not see these frames. During development it sometimes helps to give them distinctive colors to help you visualize. Once you get everything working, you can adjust the colors to their final values.
Add the entry widgets
Now we can add the entry widgets to the top half of the bottom section. We can use grid here, since everything is lined up neatly. An important step is to give the rows an equal weight so that they grow and shrink together, though you can make it so that only one column resizes if you wish.
I'll also point out that there's no need to use StringVar instance. You can, but it adds extra objects to keep track of, which in most cases is not necessary.
label1 = tk.Label(inputFrame, text="APPLICATION ID",
foreground="lightgray",
background="#2C2F33")
label2 = tk.Label(inputFrame, text="LARGE IMAGE HOVER",
foreground="lightgray",
background="#2C2F33")
label3 = tk.Label(inputFrame, text="SMALL IMAGE HOVER",
foreground="lightgray",
background="#2C2F33")
# columns should get extra space equally. Give any extra vertical space
# to an empty column below the entry widgets
inputFrame.grid_columnconfigure((0,1,2), weight=1)
inputFrame.grid_rowconfigure(2, weight=1)
appIdEntry = tk.Entry(inputFrame, borderwidth=0,
highlightthickness=0,
background="#23272A", bd=0)
largeImageEntry = tk.Entry(inputFrame,
highlightthickness=0,
background="#23272A", bd=0)
smallImageEntry = tk.Entry(inputFrame, borderwidth=0,
highlightthickness=0,
background="#23272A", bd=0)
label1.grid(row=0, column=0, sticky="w")
label2.grid(row=0, column=1, sticky="w", padx=10)
label3.grid(row=0, column=2, sticky="w")
appIdEntry.grid(row=1, column=0, sticky="ew")
largeImageEntry.grid(row=1, column=1, sticky="ew", padx=10)
smallImageEntry.grid(row=1, column=2, sticky="ew")
This gives us the following:
Notice that the top appears to have shrunk. That's only because it's empty. Tkinter is really good about expanding and shrinking things to fit what's inside. Don't worry too much about it. You can tweak things once you get everything working.
And so on...
I don't want to rewrite your whole program in this answer. The point here is that you should break your UI up into logical chunks, and make each chunk a frame. You are then free to use whatever geometry manager makes the most sense within that frame. Sometimes grid is best, sometimes pack. In either case, it's much easier to manage a few high level frames than it is to try to cram dozens of widgets into a single grid, especially when there are no clear cut rows and/or columns.
This solution also makes it pretty easy to create functions or classes for each section. For example, your main program might look like:
root = tkinter.Tk()
top = topSection(root)
bottom = bottomSection(root)
By doing so, if you decide to completely redesign one section of the UI, you can do so without worrying that you'll mess up the layout in the other sections, since each frame is mostly independent of any other frame.
First you have to explain to the grid geometry manager that you want the canvas to span all three columns:
topCanvas.grid(row=0, column=1, columnspan=3)
Widgets do not automatically expand to fill the entire column (or row) if you don't specify it and it will center itself in a cell if you dont specify where you want it with sticky:
newProfileButton.grid(row=5, column=1, padx=(20, 5), sticky='w')
saveButton.grid(row=5, column=2, padx=(5, 5), sticky='w')
loadButton.grid(row=5, column=3, padx=(5, 20), sticky='w')
This will hopefully give you something to play with although it's not a complete answer.
Here is a good tutorial: Getting Tkinter Grid Sizing Right the first time
How do I align my Radiobuttons? I can add spaces to test4 but that solution doesn't seem proper. Here's what it looks like at the moment—as you can see text111111 has extra chars. I've tried using padx.
My code:
from tkinter import *
class GUI:
def __init__(self, master):
self.iconnum = IntVar()
self.master = master
self.master.title('test')
self.master.resizable(width=False, height=False)
self.master.maxsize(500, 250)
self.master.minsize(500, 250)
self.test1 = Radiobutton(master, text="test11111111", variable=self.iconnum,
value=1, )
self.test2 = Radiobutton(master, text="test2", variable=0, value=2, )
self.test3 = Radiobutton(master, text="test3", variable=0, value=3, )
self.test4 = Radiobutton(master, text="test4", variable=0, value=4)
self.test1.grid(row=2, columnspan=1)
self.test2.grid(row=2, columnspan=2)
self.test3.grid(row=2, column=1)
self.test4.grid(row=3, columnspan=1)
self.Checker = Radiobutton(master, text="test5", indicatoron=0, height=1, width=35,
value=0, command=self.icon_switcher) #var=Selection)
self.Turbo = Radiobutton(master, text="test6", indicatoron=0, height=1, width=35,
value=1, command=self.icon_switcher) #var#=Selection)
self.Checker.grid(row=1)
self.Turbo.grid(row=1, column=1, )
def icon_switcher(self):
print("Hello")
root = Tk()
gui = GUI(root)
root.mainloop()
You should use the sticky keyword argument in order to align your widgets better when using grid.
import Tkinter as tk
window = tk.Tk()
radio = tk.Radiobutton(window, text="I'm a radio")
radio.grid(column=0, row=0, sticky=tk.N+tk.S+tk.W+tk.E)
window.mainloop()
You can use any combination of the N, S, W and E members of the Tkinter module. This parameter will make your widgets stick to the sides of the cell you have specified, somewhat like justification in text. If your widget is resizable, such as with Button, the widget will also automatically resize to fit the cell if you use all of the N, S, W and E members.
Important to note is that this can only do so much as to make the widgets stick to the edges of the cell. Sometimes it is necessary to actually resize the cell or move your widget to another cell.
In your example image, you have Buttons with a set size that is larger than the default size (the example code you provide is incomplete). This causes the cell, and the whole columns that the cells of these Buttons are in, to become wider. In this case, you might want to use the columnspan keyword argument to divide your column into smaller, resizable, parts, so that your Radiobuttons can be aligned still better.
import Tkinter as tk
window = tk.Tk()
radio_one = tk.Radiobutton(window, text="I'm a radio")
radio_two = tk.Radiobutton(window, text="I'm another radio")
button = tk.Button(window, text="I am a very long button", width=50)
button.grid(row=0, column=0, columnspan=2, sticky=tk.N+tk.S+tk.W+tk.E)
radio_one.grid(column=0, row=1, sticky=tk.N+tk.W)
radio_two.grid(column=1, row=1, sticky=tk.N+tk.W)
window.mainloop()
If you would like more information on what parameters the grid geometry manager can use, I suggest you read this tutorial, I have found it to be very helpful in the past.
As a sidenote, please note that you use the variable keyword argument in the declaration of your Radiobuttons incorrectly. You must pass either a tk.StringVar, tk.IntVar or some other comparable object, as described here.
You can use sticky=W inside your .grid for all your buttons to make them align on the left side. And you can also include pady = 20 to make it not go all the way to the left.
I want to put a small image and other widgets over a canvas on which an image is displayed. I've tried options such ascompound and other things.
Background picture is fine and the small image that I want to put over the background image shows fine but it's always top or bottom of the window. I want it to be placed over any area of background image. I've tried many options of all the geometry manager (pack, grid, place) but none of them works. Please help, here's my code :
from Tkinter import *
root = Tk()
root.iconbitmap('E:/a.ico')
root.title('Unick Locker')
canvas = Canvas(root, width=730, height=600)
canvas.grid()
bgImg = PhotoImage(file="E:/a.gif")
canvas.create_image(370, 330, image=bgImg)
login = PhotoImage(file="E:/login.gif")
lo = Label(root, image=login)
lo.grid()
root.mainloop()
In order to add any widgets over or the foreground of any background image or canvas, the row and column values of all the widgets must be same as of the background image. so, my above mentioned program would be like this :
from Tkinter import *
root = Tk()
root.iconbitmap('E:/a.ico')
root.title('Unick Locker')
canvas = Canvas(root, width=730, height=600)
canvas.grid(row=0, column=0)
bgImg = PhotoImage(file="E:/a.gif")
canvas.create_image(370, 330, image=bgImg)
login = PhotoImage(file="E:/login.gif")
lo = Label(root, image=login)
lo.grid(row=0, column=0)
root.mainloop()
I tried putting the same row and column values to the widgets in grid() methods which I wanted to put over the image, and it worked fine as I wanted :-)
Have you considered using the paste method, which lets you define the position of the pasted image through a box argument?
See http://effbot.org/imagingbook/imagetk.htm.
Please also take a look at this thread: Tkinter, overlay foreground image on top of a background image with transparency, which seems very similar to your issue.
You are looking to draw the widgets over the canvas, this means you must specify the canvas as the parent widget, not the root as you did. For that, modify lo = Label(root, image=login) to lo = Label(canvas, image=login)
Also, do not forget to specify the rows and columns where you want to position the different widgets. This means you need to write, for example, lo.grid(row=0, column=0) instead of lo.grid(). For the moment you do not see big problems because you have only one label widget. But if you try to add an other widget without mentioning the exact positions (rows and columns) you will get unexpected results.
This question isn't about images at all, it's just a basic layout problem. You'll have the same issues with or without images. The problem is simply that you aren't giving any options to grid, so it naturally puts things at the top. Tkinter also has the behavior that a containing widget (eg: your canvas) will shrink or expand to exactly fit its contents.
Here's a version that creates several widgets over a background image. Notice the use of options to pack and grid, and the use of grid_rowconfigure and grid_columnconfigure to specify how extra space is allocated.
from Tkinter import *
root = Tk()
canvas = Canvas(root, width=730, height=600)
canvas.pack(fill="both", expand=True)
bgImg = PhotoImage(file="E:/a.gif")
canvas.create_image(370, 330, image=bgImg)
l1 = Label(canvas, text="Hello, world")
e1 = Entry(canvas)
t1 = Text(canvas)
l1.grid(row=0, column=0, sticky="ew", padx=10)
e1.grid(row=1, column=1, sticky="ew")
t1.grid(row=2, column=2, sticky="nsew")
canvas.grid_rowconfigure(2, weight=1)
canvas.grid_columnconfigure(2, weight=1)
root.mainloop()