usually buttons in tkinter center their texts automatically but i can't seem to get it i don't know why!
from tkinter import *
from tkinter import messagebox
from PIL import Image,ImageTk
from getpass import getpass
huh=Tk()
huh.title('Login page')
huh.configure(bg='white')
huh.resizable(False,700)
huh.geometry('925x500+300+200')
my_fr=Frame(huh,width=350,height=350,bg='white')
my_fr.place(x=480,y=90)
btn=Button(my_fr,width=50,border=0,text="Connexion",bg='#000000',fg="#ffffff",font='Railway',anchor=CENTER)
btn.place(x=43,y=300)
huh.mainloop()
Here is a solution using grid() that positions the button, with text centered, at the x, y coordinates used with the original place() statement.
Note that resizeable() takes only boolean parameters, so '700' would be interpreted as True. Assuming that a maximum window height of 700 with a minimum height of 500 was the intention, resizeable() was replaced with minsize() and maxsize() statements.
The geometry() statement was retained, but if the system's default window position is suitable, then it can be removed.
Replacing my_fr.grid() with my_fr.pack() would horizontally center the button, thus ignoring the padx specification.
import tkinter as tk
huh = tk.Tk()
huh.title('Login page')
huh.configure(bg='white')
huh.geometry('925x500+300+200')
huh.minsize(925, 500)
huh.maxsize(925, 700)
my_fr = tk.Frame(huh, bg='white')
btn = tk.Button(my_fr, width=50, text="Connexion",
bg='black', fg="white", font='Railway')
my_fr.grid()
btn.grid(padx=43, pady=300)
huh.mainloop()
Related
from tkinter import*
window = Tk()
color=['red','blue','purple']
def chgcolor():
for i in color:
mybutton.config(bg=i)
window.title('my first python gui')
mybutton=Button(window,text='change color',command=chgcolor)
mybutton.pack()
window.mainloop()
I'm trying to make the button change colors to red, then blue, then purple, then back to the original color every time I click the button, but for now, it only turns purple no matter how many times I click it. Any help?
You don't need to use for loop inside chgcolor(). Use itertools.cycle() on the colors and next(color) to get the next color and update the button inside chgcolor():
# avoid using wildcard import
import tkinter as tk
from itertools import cycle
window = tk.Tk()
window.title('my first python gui')
def chgcolor():
# get the next color from the color list
mybutton.config(bg=next(color))
mybutton = tk.Button(window, text='change color', command=chgcolor)
mybutton.pack()
# create a color cycle list
color = cycle(['red','blue','purple',mybutton['bg']])
window.mainloop()
The problem is simple. The scrolled text box will be written into it in Arabic.
So I need to align the text whenever I type to the right of the box. There isn't any attribute, such as justify. Also I used a tag, but I couldn't do it.
show_note = scrolledtext.ScrolledText(canvas, width=int(monitorWidth / 65), height=int(monitorHeight / 130),
font=("Times New Roman", 14))
canvas.create_window(cord(0.45, 0.65), window=show_note, anchor="ne")
Is there an alternative to the scrolled text control, but that has these attributes (width, height, justify and can write into multiple lines)?
I did some searching and could not find any other way to do this, than to bind each keypress to a function, that adds/edits the tag to select all the item from the text box:
from tkinter import *
from tkinter import scrolledtext
root = Tk()
def tag(e):
text.tag_add('center','1.0','end')
text = scrolledtext.ScrolledText(root)
text.pack()
text.tag_config('center',justify='right')
text.bind('<KeyRelease>',tag)
root.mainloop()
You can also make your custom widget that does this, instead of repeating code for each file, so a more better form would be:
from tkinter import *
from tkinter import scrolledtext
root = Tk()
class JustifyText(scrolledtext.ScrolledText):
def __init__(self,master,*args,**kwargs):
scrolledtext.ScrolledText.__init__(self,master,*args,**kwargs)
self.tag_config('center',justify='right')
self.bind('<KeyRelease>',self.tag)
def tag(self,e):
text.tag_add('center','1.0','end')
text = JustifyText(root)
text.pack()
root.mainloop()
And yes you can make this more perfect by taking the current width of text box and shifting the insertion cursor to that point, to make it start from that point.
Import a tkinter OptionMenu who's background colour changes based on selection.
The below code creates a tkinter OptionMenu whos background colour changes based on the selection chosen from the dropdown menu. It works as I want it too as is.
But, how do I make this OptionMenu re-usable? So that I can import it into my main .py file from a different .py file.
I've been trying different things and reading for days about how to do this and haven't been able to figure it out. I've read about turning functions into classes and variables into functions etc. and importing those. However, I have been unable t get it quite right and am stumped.
import tkinter
HEIGHT = 700
WIDTH = 1100
m = tkinter.Tk()
from lists import lbmenuopt
canvas = tkinter.Canvas(m, height=HEIGHT, width=WIDTH,)
canvas.pack()
#selected item variable
clicked1 = tkinter.StringVar()
# function that changes background color based on selection
def lbmenubg(clicked1):
if clicked1 == "---":
lbmenu.configure(bg="#777777", activebackground="#777777")
elif clicked1 == "LB":
lbmenu.configure(bg="#D35400", activebackground="#D35400")
elif clicked1 == "Sign":
lbmenu.configure(bg="#D35400", activebackground="#D35400")
else:
lbmenu.configure(bg="#196F3D", activebackground="#196F3D")
# Option Menu settings and placement
lbmenu = tkinter.OptionMenu(m, clicked1, *lbmenuopt, command= lambda x: lbmenubg(clicked1.get()))
lbmenu.config(bg="#777777", foreground="white", activeforeground="white", activebackground="#777777",
borderwidth=0, relief="flat", bd=0)
lbmenu['menu'].config(bg="#e4e4e4", fg="black", activebackground="white", activeforeground="#3b4045",)
lbmenu.place(relx=0.125, rely=.03, relwidth=0.065, relheight=0.03)
m.mainloop()
I'm getting vertical alignment of entries while using the following code
from Tkinter import *
import tkMessageBox
import Tkinter
top = Tk()
Lb1 = Listbox(top)
Lb1.insert(1, "Python")
Lb1.insert(2, "Perl")
Lb1.insert(3, "C")
Lb1.insert(4, "PHP")
Lb1.insert(5, "JSP")
Lb1.insert(6, "Ruby")
Lb1.pack()
top.mainloop()
Is it possible to allign listbox entries horizontally? or any other widget can be used for it??
Thanks
Usually a separate listbox is used for each item (especially if you want to select one option from one category). Note that the size that width= uses depends on the font size, and that the distances will be close but not exact unless you use a fixed width font ("i" takes up the same amount of space as "w").
from Tkinter import *
top = Tk()
for lit in ("Python", "Perl", "C", "PHP", "JSP", "Ruby"):
lb=Listbox(top,width=10)
lb.pack(side=LEFT)
lb.insert(1, lit)
top.mainloop()
You can use the grid geometry manager to lay things out in a grid, or you can pass a value in for the side parameter using pack (eg: Lb1.pack(side="left"))
...
self.myListbox=tkinter.Listbox()
self.myListbox.pack()
self.myButton=tkinter.Button(self.myListbox,text="Press")
self.myListbox.insert(1,myButton.pack())
...
I want to insert a button into listbox like inserting a sting. How can I do this?
You can't. From the listbox documentation: "A listbox is a widget that displays a list of strings".
You can, of course, use pack, place or grid to put a button inside the widget but it won't be part of the listbox data -- it won't scroll for example, and might obscure some of the data.
An alternative to a ListBox is a scrollable frame;
import functools
try:
from tkinter import *
import tkinter as tk
except ImportError:
from Tkinter import *
import Tkinter as tk#
window = Tk()
frame_container=Frame(window)
canvas_container=Canvas(frame_container, height=100)
frame2=Frame(canvas_container)
myscrollbar=Scrollbar(frame_container,orient="vertical",command=canvas_container.yview) # will be visible if the frame2 is to to big for the canvas
canvas_container.create_window((0,0),window=frame2,anchor='nw')
def func(name):
print (name)
mylist = ['item1','item2','item3','item4','item5','item6','item7','item8','item9']
for item in mylist:
button = Button(frame2,text=item,command=functools.partial(func,item))
button.pack()
frame2.update() # update frame2 height so it's no longer 0 ( height is 0 when it has just been created )
canvas_container.configure(yscrollcommand=myscrollbar.set, scrollregion="0 0 0 %s" % frame2.winfo_height()) # the scrollregion mustbe the size of the frame inside it,
#in this case "x=0 y=0 width=0 height=frame2height"
#width 0 because we only scroll verticaly so don't mind about the width.
canvas_container.pack(side=LEFT)
myscrollbar.pack(side=RIGHT, fill = Y)
frame_container.pack()
window.mainloop()