how to replace text in tkinter? - python

I'm making a wrong-word corrector so I use replace method, but it doesn't work
because it is not all same word.
For example:
string = i like icecream
I want to change the word = icecream
It only works for "i like icecream" if it is all the same
This is my whole code:
# coding: utf-8
from tkinter import *
import tkinter.messagebox
root=Tk()
root.title("words corrector")
root.resizable(0, 0)
root.geometry("+{}+{}".format(600, 400))
mainFrame = Frame(root, width=600, height=400)
mainFrame.pack()
textFrame = Frame(mainFrame, width=100, height=100)
textFrame.pack()
textFrame_1 = Frame(mainFrame, width=100, height=100)
textFrame_1.pack()
textFrame_2 = Frame(mainFrame,width=100, height=100)
textFrame_2.pack()
scrollbar = Scrollbar(textFrame)
scrollbar.pack(side=RIGHT, fill="y")
#textField == sentance
textField = Text(textFrame, width=50, height=10, bd=5, relief="groove")
textField.insert(CURRENT,"enter the text\n")
textField.pack(side=LEFT, padx=(5, 0), pady=(5, 5))
textField["yscrollcommand"] = scrollbar.set
#textField_2 == wrong word
textField_2= Text(textFrame_1, width=15, height=3, bd=5, relief="groove")
textField_2.insert(CURRENT,"wrong words\n")
textField_2.pack(side=LEFT, padx=(5,0), pady=(5,5))
#textField_3 == correct word
textField_3= Text(textFrame_1,width=15, height=3, bd=5, relief="groove")
textField_3.insert(CURRENT, "correct words\n")
textField_3.pack(side=LEFT, padx=(5,0), pady=(5,5))
def chg():
sentance = textField.get("1.0",END)
wrong_word = textField_2.get("1.0",END)
correct_word = textField_3.get("1.0",END)
result = sentance.replace(wrong_word,correct_word)
textField_4.insert("1.0",result)
def msg():
tkinter.messagebox.showerror("error","there's no words")
def ok():
if textField_2.get("1.0",END) in textField.get("1.0",END):
chg()
else:
msg()
okButton = Button(textFrame_1, text="OK", command=ok)
okButton.pack(padx=40, pady=(20,5))
scrollbar_2 = Scrollbar(textFrame_2)
scrollbar_2.pack(side=RIGHT, fill="y")
textField_4 = Text(textFrame_2, width=50, height=10, bd=5, relief="groove")
textField_4.pack(side=LEFT, padx=(5, 0), pady=(5, 5))
textField_4["yscrollcommand"] = scrollbar.set
root.mainloop()

Try the following code. You have to convert unicode characters to a string and use str.replace.
from tkinter import *
import tkinter.messagebox
root=Tk()
root.title("words corrector")
root.resizable(0, 0)
root.geometry("+{}+{}".format(600, 400))
mainFrame = Frame(root, width=600, height=400)
mainFrame.pack()
textFrame = Frame(mainFrame, width=100, height=100)
textFrame.pack()
textFrame_1 = Frame(mainFrame, width=100, height=100)
textFrame_1.pack()
textFrame_2 = Frame(mainFrame,width=100, height=100)
textFrame_2.pack()
scrollbar = Scrollbar(textFrame)
scrollbar.pack(side=RIGHT, fill="y")
#textField == sentance
textField = Text(textFrame, width=50, height=10, bd=5,
relief="groove")
textField.insert(CURRENT,"enter the text\n")
textField.pack(side=LEFT, padx=(5, 0), pady=(5, 5))
textField["yscrollcommand"] = scrollbar.set
#textField_2 == wrong word
textField_2= Text(textFrame_1, width=15, height=3, bd=5,
relief="groove")
textField_2.insert(CURRENT,"wrong words\n")
textField_2.pack(side=LEFT, padx=(5,0), pady=(5,5))
#textField_3 == correct word
textField_3= Text(textFrame_1,width=15, height=3, bd=5,
relief="groove")
textField_3.insert(CURRENT, "correct words\n")
textField_3.pack(side=LEFT, padx=(5,0), pady=(5,5))
scrollbar_2 = Scrollbar(textFrame_2)
scrollbar_2.pack(side=RIGHT, fill="y")
textField_4 = Text(textFrame_2, width=50, height=10, bd=5,
relief="groove")
textField_4.pack(side=LEFT, padx=(5, 0), pady=(5, 5))
textField_4["yscrollcommand"] = scrollbar.set
def chg():
sentance = textField.get("1.0",END)
wrong_word = textField_2.get("1.0",END)
correct_word = textField_3.get("1.0",END)
# result = sentance.replace(wrong_word,correct_word)
result = str.replace(str(sentance), wrong_word, correct_word)
textField_4.insert("1.0",result)
def msg():
tkinter.messagebox.showerror("error","there's no words")
def ok():
# if textField_2.get("1.0",END) in textField.get("1.0",END):
chg()
# else:
# msg()
okButton = Button(textFrame_1, text="OK", command=ok)
okButton.pack(padx=40, pady=(20,5))
root.mainloop()
OUTPUT:
EDIT
If you want want to keep that "enter the text part" and type your sentence below, without replacing it, you should do the following in the relevant line for the code to work.
result = str.replace(str(sentance).replace('enter the text\n',''), wrong_word.replace('wrong words\n',''), correct_word.replace('correct words\n',''))

Related

scrollbar not working for an inner frame inside a canvas

I am trying to build a pattern for question paper...
I created a canvas in a frame and added a scrollbar. I created another frame inside and set the scrollbar to it. THe pattern for a question is in a frames which is repeated on the inner frame as per choice of user.
But the scrollbar is not working here, so after the question pattern has crossed the page, I cannot view them.
Here is a shortened form of my code.....
from tkinter import *
from tkinter import ttk
home = Tk()
width = home.winfo_screenwidth() - 20
height = home.winfo_screenheight() - 100
home.wm_geometry(f"{width}x{height}")
home.state("zoomed")
frame1 = Frame(home, bg='RED')
frame2 = Frame(home, bg='yellow')
frame1.pack(fill=Y, side=LEFT)
frame2.pack(fill=BOTH, expand=YES, side=LEFT)
label1 = Label(frame1, text="Label for Frame1", bg='light blue')
label1.grid(row=0, column=0)
def handle_resize(event):
canvas = event.widget
canvas_frame = canvas.nametowidget(canvas.itemcget("canvas_frame", "window"))
min_width = canvas_frame.winfo_reqwidth()
min_height = canvas_frame.winfo_reqheight()
if min_width < event.width:
canvas.itemconfigure("canvas_frame", width=event.width)
if min_height < event.height:
canvas.itemconfigure("canvas_frame", height=event.height)
canvas.configure(scrollregion=canvas.bbox("all"))
question_type_canvas = Canvas(frame2, bg='light green')
question_type_canvas.pack(side=LEFT, expand=YES, fill=BOTH)
inner_question_type_frame = Frame(question_type_canvas)
question_type_canvas.create_window((0, 0), window=inner_question_type_frame, anchor='nw', tags=("canvas_frame",))
vbar = Scrollbar(frame2, orient=VERTICAL, command=question_type_canvas.yview())
vbar.pack(side=RIGHT, fill=Y)
question_type_canvas.configure(yscrollcommand=vbar.set)
question_type_canvas.bind('<Configure>', handle_resize)
def clone_question_types(ques_index, row_number):
question_type_frame = Frame(inner_question_type_frame, bg='light pink')
question_type_frame.grid(row=row_number, column=0)
question_types_dict = dict({'Multiple Choice Questions': 1,
'Fill in the Blanks': 2})
question_types_combo_values = list(question_types_dict.keys())
question_no_label = Label(question_type_frame, text=f'Q {ques_index + 1}', bg='light pink', width=5)
type_label = Label(question_type_frame, text='Type: ', width=20, padx=5, bg='light pink')
type_selected = StringVar(question_type_frame)
type_menu = ttk.Combobox(question_type_frame, textvariable=type_selected,
values=list(question_types_combo_values), width=20, state="readonly")
next_question_button = Button(question_type_frame, text='Next Question',
command=lambda: [next_question_button.configure(state=DISABLED),
clone_question_types(ques_index + 1, row_number + 1)])
question_no_label.grid(row=0, column=0, sticky='w')
type_label.grid(row=0, column=1, sticky='w')
type_menu.grid(row=0, column=2, sticky='w')
next_question_button.grid(row=3, column=1)
clone_question_types(0, 0)
home.mainloop()

Python tkinter get function

I have two python files - main.py and dictionary.py . I am creating an 8 in 1 app. When I run dictionary.py, I can get the meaning of the desired word but while running main.py, the value of the variables gets lost.
While running main.py, the value of text_v gets reset. But while running only dictionary.py, the value of text_v remains the same. I don't know why it is happening. Please help
main.py
import tkinter as tk
from PIL import ImageTk, Image
import dictionary as dc
win = tk.Tk()
win.geometry("1280x720+100-100")
calc_icon = Image.open("calculator_icon.png")
calc_icon = ImageTk.PhotoImage(calc_icon)
print(type(calc_icon))
calc_button = tk.Button(win, image=calc_icon, borderwidth=0)
calc_button.place(x=160, y=180, anchor='center')
timetable_icon = Image.open("timetable_icon.png")
timetable_icon = ImageTk.PhotoImage(timetable_icon)
timetable_button = tk.Button(win, image=timetable_icon, borderwidth=0)
timetable_button.place(x=480, y=180, anchor='center')
texteditor_icon = Image.open("texteditor_icon.png")
texteditor_icon = ImageTk.PhotoImage(texteditor_icon)
texteditor_button = tk.Button(win, image=texteditor_icon, borderwidth=0)
texteditor_button.place(x=800, y=180, anchor='center')
dictionary_icon = Image.open("dictionary.png")
dictionary_icon = ImageTk.PhotoImage(dictionary_icon)
dictionary_button = tk.Button(win, image=dictionary_icon, borderwidth=0, command=dc.dic)
dictionary_button.place(x=1120, y=180, anchor='center')
budget_icon = Image.open("budgetmanager.png")
budget_icon = ImageTk.PhotoImage(budget_icon)
budget_button = tk.Button(win, image=budget_icon, borderwidth=0)
budget_button.place(x=160, y=450, anchor='center')
todo_icon = Image.open("todo.png")
todo_icon = ImageTk.PhotoImage(todo_icon)
todo_button = tk.Button(win, image=todo_icon, borderwidth=0)
todo_button.place(x=480, y=450, anchor='center')
bookmark_icon = Image.open("bookmark.png")
bookmark_icon = ImageTk.PhotoImage(bookmark_icon)
bookmark_button = tk.Button(win, image=bookmark_icon, borderwidth=0)
bookmark_button.place(x=800, y=450, anchor='center')
news_icon = Image.open("news.png")
news_icon = ImageTk.PhotoImage(news_icon)
news_button = tk.Button(win, image=news_icon, borderwidth=0)
news_button.place(x=1120, y=450, anchor='center')
win.mainloop()
dictionary.py
import tkinter as tk
import PyDictionary as pd
def dic():
def click():
m_canvas = tk.Canvas(win)
print('line 12', text_v)
word = text_v.get()
print(word)
m_canvas.place(x=300, y=0)
m_label = tk.Label(m_canvas, text='Meaning', font=('Callibri', 20))
m_label.grid(row=0, column=0)
translated = pd.PyDictionary.meaning(word)
print(translated)
meaning = tk.Label(m_canvas, text=translated, font=('Callibri', 15))
meaning.grid(row=1, column=0)
win = tk.Tk()
win.title('Dictionary')
win.geometry('1280x720+100-100')
text_v = tk.StringVar()
print('line 31', text_v)
canvas = tk.Canvas(win)
canvas.place(x=0, y=0, anchor='nw')
head = tk.Label(canvas, text='Dictionary:', font=('Callibri, 20'))
head.grid(row=0, column=0)
lab = tk.Label(canvas, text='Enter a word', font=('Callibri', 20))
lab.grid(row=1, column=0)
inp = tk.Entry(canvas, textvariable=text_v)
inp.grid(row=2, column=0)
lab2 = tk.Label(canvas, text='')
lab2.grid(row=3, column=0)
btn = tk.Button(canvas, text='Submit', command=click)
btn.grid(row=4, column=0)
win.mainloop()

How to update LabelFrame title (Tkinter)

I am a novice and working with Tkinter for the first time. My project is an "I Spy" book which moves picture to picture utilizing buttons. I like the look of the LabelFrame widget and want to use the title for the text that corresponds with each image. I am able to achieve the images updating correctly but the title remains the same. I have tried config, forgetting and then rebuilding the frame, and I think something else which I can't recall and none of that has worked. I have searched online, reviewed Stack Overflow similar questions--which are very few and lead me to believe that this cannot be done. Thank you for your assistance.
from tkinter import *
from tkinter import Button
from tkinter import Label
from PIL import ImageTk
from PIL import Image
root = Tk()
root.title('')
root.attributes('-toolwindow', True)
root.geometry('620x660+100+0')
img2 = ImageTk.PhotoImage(Image.open('spy_images/rainbow.jpg'))
img4 = ImageTk.PhotoImage(Image.open('spy_images/pods.jpg'))
img5 = ImageTk.PhotoImage(Image.open('spy_images/lion.jpg'))
img6 = ImageTk.PhotoImage(Image.open('spy_images/bike.jpg'))
img7 = ImageTk.PhotoImage(Image.open('spy_images/binary.jpg'))
image_list = [img2, img4, img5, img6, img7]
text2 = 'A rainbow, not in the sky!'
text4 = 'Dangly, weird seed pods.'
text5 = 'A stoney grin.'
text6 = 'A lane just for bikes.'
text7 = 'A different way to count.'
text_list = [text2, text4, text5, text6, text7]
make_frame = LabelFrame(root, text='A rainbow, not in the sky!', width=100, height=100,
font=('Arial', 14, 'bold'), fg='red', bd=10)
make_frame.grid(row=0, column=1, columnspan=5)
img_filename = 'spy_images/rainbow.jpg'
PIL_image = Image.open(img_filename)
img = ImageTk.PhotoImage(PIL_image)
in_frame = Label(make_frame, image=img)
in_frame.grid(padx=10, pady=10)
def forward(image_num, text_num):
global make_frame
global in_frame
global button_forward
global button_back
in_frame.grid_forget()
in_frame = Label(image=image_list[image_num])
button_forward = Button(root, text='>>', command=lambda:
forward(image_num+1, text_num+1))
button_back = Button(root, text='<<', command=lambda:
back(image_num-1, text_num-1))
if image_num == 7:
button_forward = Button(root, text='>>', state=DISABLED)
make_frame.grid(row=0, column=1, columnspan=5)
in_frame.grid(row=0, column=0, columnspan=5)
in_frame.grid(padx=10, pady=10)
button_forward.grid(row=1, column=5)
button_back.grid(row=1, column=1)
button_back.grid_columnconfigure(0, weight=1)
button_back.grid_columnconfigure(2, weight=1)
button_back.grid_columnconfigure(4, weight=1)
def back(image_num, text_num):
global make_frame
global in_frame
global button_forward
global button_back
in_frame.grid_forget()
in_frame = Label(image=image_list[image_num - 1])
button_forward = Button(root, text='>>', command=lambda:
forward(image_num + 1, text_num + 1))
button_back = Button(root, text='<<', command=lambda:
back(image_num - 1, text_num - 1))
if image_num == 1:
button_back = Button(root, text='<<', state=DISABLED)
make_frame.grid(row=0, column=1, columnspan=5)
in_frame.grid(row=0, column=0, columnspan=3)
in_frame.grid(padx=10, pady=10)
button_forward.grid(row=1, column=5)
button_back.grid(row=1, column=1)
button_back.grid_columnconfigure(0, weight=1)
button_back.grid_columnconfigure(2, weight=1)
button_back.grid_columnconfigure(4, weight=1)
button_back = Button(root, text='<<', command=back, state=DISABLED, bg='#d9d5d4',
font=('Arial', 14, 'bold'))
button_exit = Button(root, text='Cancel', command=root.quit, bg='#d9d5d4', font=('Arial', 12))
button_forward = Button(root, text='>>', command=lambda: forward(2, 2), bg='#d9d5d4', font=('Arial', 14, 'bold'))
button_back.grid(row=1, column=1)
button_exit.grid(row=1, column=3)
button_forward.grid(row=1, column=5)
button_back.grid_columnconfigure(0, weight=1)
button_back.grid_columnconfigure(2, weight=1)
button_back.grid_columnconfigure(4, weight=1)
root.mainloop()
If you have some questions about the exampel I'll try to answer you.
import tkinter as tk
#you dont need this but if you want to cycle, wich is would be nice there you go
from itertools import cycle
#create a list with strings you like to display
li = ['A rainbow, not in the sky!','Dangly, weird seed pods.','A stoney grin.',
'A lane just for bikes.','A different way to count.']
#here we create a cycle of that list
my_cycled_li = cycle(li)
#the change function
def change():
#set var to next element in list
var.set(next(my_cycled_li))
#update the LabelFrame
lf.configure(text=var.get())
root = tk.Tk()
#variable to change
var = tk.StringVar()
#there can be a default setting
var.set('default')
lf = tk.LabelFrame(root,text=var.get(),width=200,height=100,bg='red')
#you dont need this, this means the Frame size isnt the size of the widget it contains.
lf.pack_propagate(0)
lf.pack()
b = tk.Button(lf,text='change', command=change)
b.pack()
root.mainloop()
hoped it helps.

Tkinter, alignment - the endless question

Since some days I'll try to align these two items inside a Tkinter frame:
The pink part should be on the left and the green button on the right. With HtmlDivs and CSS a question of seconds, with TKinter a pain in the ...
Here is my python code:
import tkinter as tk
root = tk.Tk()
root.geometry("400x200")
buttons = tk.Frame(root)
buttons.pack(side="top", expand=True, fill='both')
label = tk.Label(buttons, text="Hello, world", anchor='w', background='pink')
b2 = tk.Button(buttons, text="EXIT", background='green')
label.grid(row=0, column=1, sticky='w', ipadx = '20', padx = '20')
b2.grid(row=0, column=3, sticky='e', ipadx = '20', padx = '20')
root.mainloop()
The final app will be running fullscreen on a 7" touch display.
The simplest solution is to use pack instead of grid, since you only have a single row of widgets inside of buttons. pack's strength is arranging things in a single row or a single column.
Just remove these two lines:
label.grid(row=0, column=1, sticky='w', ipadx = '20', padx = '20')
b2.grid(row=0, column=3, sticky='e', ipadx = '20', padx = '20')
... and replace them with this:
label.pack(side='left')
b2.pack(side='right')
Also, since you appear to be creating a toolbar, you want to leave expand as False and set fill to just "x", otherwise the toolbar will expand to fill the entire window:
buttons.pack(side="top", expand=False, fill='x')
Thx for your tips,
this is just a testcode to update my maincode.
Its not good to mix .pack and .grid, right ? If i do, the script crashes completely,
so ill have to re-do my mainscript i think.
This is what i need:
row: 1/2: label (it will be a real time clock) left 2/2: exit button (exit fullscreen) right
row: 1/3: image (weather), 2/3: weather data (label), 3/3: calendar
row: 4 buttons: 1. lightoff 2. light25%, 3.light50% 4.light100&
Thats it basically all is working, it just need to align it (im a coding hero g)
Since i have the frame from the code above, i thought i can easily add 2. & 3. row with another frames, but that does not seem to work ??
Preview:
https://i.stack.imgur.com/KzoqV.png
My (main)Code so far
root = Tk()
root.title('Model Definition')
root.config(background = "deepskyblue4")
root.attributes('-fullscreen',True)
root.bind('<Escape>',lambda e: root.destroy())
def currenttime():
string = strftime("%A, %d.%B.%Y %H:%M:%S")
lbl.config(text = string, background = 'deepskyblue4', fg='white', font=("colibri", 30))
lbl.after(1000, currenttime)
def light400():
FNULL = open(os.devnull, 'w')
subprocess.call(['gpio -g pwm 18 401'], stdout=FNULL, stderr=subprocess.STDOUT, shell=True)
def light425():
FNULL = open(os.devnull, 'w')
subprocess.call(['gpio -g pwm 18 425'], stdout=FNULL, stderr=subprocess.STDOUT, shell=True)
def light450():
FNULL = open(os.devnull, 'w')
subprocess.call(['gpio -g pwm 18 450'], stdout=FNULL, stderr=subprocess.STDOUT, shell=True)
def light475():
FNULL = open(os.devnull, 'w')
subprocess.call(['gpio -g pwm 18 500'], stdout=FNULL, stderr=subprocess.STDOUT, shell=True)
# Main frames
top_frame = Frame(root, bg='deepskyblue4', width=450, height=90, pady=3)
center = Frame(root, bg='deepskyblue2', width=50, height=40, padx=3, pady=3)
btm_frame = Frame(root, bg='deepskyblue4', width=450, height=20, pady=3)
btm_frame2 = Frame(root, bg='deepskyblue4', width=450, height=60, pady=3)
# layout all of the main containers
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)
top_frame.grid(row=0, sticky="e", padx=(10, 0))
center.grid(row=1, sticky="nsew", pady=(10, 50))
btm_frame.grid(row=3, sticky="ew")
btm_frame2.grid(row=4, sticky="ew", padx=(10, 50))
# create the widgets for the top frame
lbl = Label(top_frame, background = 'deepskyblue4', anchor=W, justify=LEFT)
lbl.pack()
currenttime()
actionbutton = Button(top_frame, text="X", width=5, height=2, bg="deepskyblue4", fg="white", command=root.destroy)
hdr_left = Frame(top_frame, bg='deepskyblue4', width=100, height=190)
hdr_right = Frame(top_frame, bg='deepskyblue4', width=400, height=190, padx=3, pady=3)
# layout the widgets in the top frame
lbl.grid(row=0, column=1, sticky="w")
actionbutton.grid(row=0, column=2, sticky="e")
# create the center widgets
center.grid_rowconfigure(0, weight=1)
center.grid_columnconfigure(1, weight=1)
ctr_left = Frame(center, bg='deepskyblue2', width=100, height=190)
ctr_mid = Frame(center, bg='deepskyblue2', width=150, height=190, padx=3, pady=3)
ctr_right = Frame(center, bg='deepskyblue2', width=400, height=190, padx=3, pady=3)
ctr_left.grid(row=0, column=0, sticky="ns")
ctr_mid.grid(row=0, column=1, sticky="nsew")
ctr_right.grid(row=0, column=2, sticky="ns")
path = "icons/rain.png"
img = ImageTk.PhotoImage(Image.open(path))
panel = Label(ctr_left, image = img, bg="deepskyblue2")
panel.grid(row=0, columnspan=3)
#imgag = panel.pack(top_frame)
#CENTER ctr_mid
if x["cod"] != "404":
y = x["main"]
y2 = x["wind"]
currenttemp = y["temp"]
currentpressure = y["pressure"]
currenthumidiy = y["humidity"]
z = x["weather"]
weather_description = z[0]["description"]
currentwind = y2["speed"]
label1 = Label(ctr_mid,text='Karlsruhe', font = ('calibri', 30), background = 'deepskyblue2')
label2 = Label(ctr_mid,text='Temperatur: '+str(round(currenttemp-272.15))+' °C', font = ('calibri', 20), background = 'deepskyblue2')
label3 = Label(ctr_mid,text='Beschreibung: '+str(weather_description),font = ('calibri', 20), background = 'deepskyblue2')
label4 = Label(ctr_mid,text='Druck: '+str(currentpressure)+' hPa', font = ('calibri', 20), background = 'deepskyblue2')
label5 = Label(ctr_mid,text='Feuchtigkeit: '+str(currenthumidiy)+' %',font = ('calibri', 20), background = 'deepskyblue2')
label6 = Label(ctr_mid,text='Wind: '+str(currentwind)+' m/Sek',font = ('calibri', 20), background = 'deepskyblue2')
label1.grid(row=0, column=0, sticky="nw")
label2.grid(row=1, column=0, sticky="nw")
label3.grid(row=2, column=0, sticky="nw")
label4.grid(row=3, column=0, sticky="nw")
label5.grid(row=4, column=0, sticky="nw")
label6.grid(row=5, column=0, sticky="nw")
# btm_frame2 widgets
licht = Label(btm_frame2, text='Licht:', width=5, height=1, bg="deepskyblue4", fg='white', font=("colibri", 20))
button = Button(btm_frame2, command=light400, text="AUS", width=5, height=1, bg="deepskyblue2", fg="white")
button2 = Button(btm_frame2, text="25 %", command=light425, width=5, height=1, bg="deepskyblue2", fg="white")
button3 = Button(btm_frame2, text="50%", command=light450, width=5, height=1, bg="deepskyblue2", fg="white")
button4 = Button(btm_frame2, text="100%", command=light475, width=5, height=1, bg="deepskyblue2", fg="white")
licht.grid(row=0, column=0, sticky="nw")
button.grid(row=0, column=1, sticky="nw")
button2.grid(row=0, column=2, sticky="nw")
button3.grid(row=0, column=3, sticky="nw")
button4.grid(row=0, column=4, sticky="nw")
actionbutton.grid(row=0, column=6, sticky="nw")
root.mainloop()

Python Tkitner : unknown option "-height". Can't change the size of button

I am trying to make a simple program using tkinter.
I was trying to change font or style of width or height.
width can be changed but when it comes to height or font - it shows mistake.
I am thinking - maybe it can be because the layout?
(The button that is changed in width is in the bottom of def initUI)
Also in case anyone can also answer this question:
I made 1 frame red because there will be error messages there but does anyone know how to make this red lie less in width?
Thank you in
from tkinter import *
from tkinter.ttk import *
class Example(Frame):
def __init__(self,master):
super().__init__()
master.minsize(width=350, height=160)
master.maxsize(width=650, height=500)
self.initUI()
def initUI(self):
self.master.title("Hank (version 3)")
self.pack(fill=BOTH, expand=True)
frame1 = Frame(self)
frame1.pack(fill=X)
#dataset
lbl1 = Label(frame1, text="Dataset file_name", width=18)
lbl1.pack(side=LEFT, padx=5, pady=5)
entryDataset= Entry(frame1)
entryDataset.pack(fill=X, padx=5, expand=True)
#row col begin
frame2 = Frame(self)
frame2.pack(fill=X)
lblRow = Label(frame2, text="Row", width=6)
lblRow.pack(side=LEFT, padx=5, pady=5)
entryRow = Entry(frame2, width=5)
entryRow.pack(side=LEFT, padx=0, expand=True)
lblCol = Label(frame2, text="Column", width=7.5)
lblCol.pack(side=LEFT, padx=5, pady=5)
entryCol = Entry(frame2, width=5)
entryCol.pack(side=LEFT, padx=5, expand=True)
lblBegin = Label(frame2, text="Start at", width=6)
lblBegin.pack(side=LEFT, padx=5, pady=5)
entryBegin = Entry(frame2, width=5)
entryBegin.pack(side=LEFT, padx=0, expand=True)
#console window
s = Style()
s.configure('My.TFrame', background='grey')
frame3 = Frame(self, style='My.TFrame')
frame3.pack(fill=BOTH, expand=True)
#button start and help
s = Style()
s.configure('My.ConsoleFrame', background='red')
frame4 = Frame(self)
frame4.pack(fill=BOTH, expand=True)
startbutton = Button(frame4, text="Start Clustering", height="100", width="100")
startbutton.pack(side=RIGHT, padx=5, pady=5)
def main():
root = Tk()
root.geometry("300x160+300+160")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
This is one of the prime examples of why global imports are bad.
You write at the top:
from tkinter import *
from tkinter.ttk import *
This means that you import everything from tkinter and tkinter.ttk into your main.py namespace. Then you write for example:
frame3 = Frame(self, bg="grey")
....
lblCol = Label(frame2, text="Column", width=7)
These are Frame/Label objects, but which ones? The one in tkinter or the one in tkinter.ttk? If it is the first, you will have to set the height with -height, else you will have to use tkinter.ttk.Style(). Same with the -bg for the frame.
Solution:
import tkinter as tk
class Example(tk.Frame):
def __init__(self,master):
super().__init__()
master.minsize(width=350, height=160)
master.maxsize(width=650, height=500)
self.initUI()
def initUI(self):
self.master.title("Hank (version 3)")
self.pack(fill=tk.BOTH, expand=True)
frame1 = tk.Frame(self)
frame1.pack(fill=tk.X)
#dataset
lbl1 = tk.Label(frame1, text="Dataset file_name", width=18)
lbl1.pack(side=tk.LEFT, padx=5, pady=5)
entryDataset= tk.Entry(frame1)
entryDataset.pack(fill=tk.X, padx=5, expand=True)
#row col begin
frame2 = tk.Frame(self)
frame2.pack(fill=tk.X)
lblRow = tk.Label(frame2, text="Row", width=6)
lblRow.pack(side=tk.LEFT, padx=5, pady=5)
entryRow = tk.Entry(frame2, width=5)
entryRow.pack(side=tk.LEFT, padx=0, expand=True)
lblCol = tk.Label(frame2, text="Column", width=7)
lblCol.pack(side=tk.LEFT, padx=5, pady=5)
entryCol = tk.Entry(frame2, width=5)
entryCol.pack(side=tk.LEFT, padx=5, expand=True)
lblBegin = tk.Label(frame2, text="Start at", width=6)
lblBegin.pack(side=tk.LEFT, padx=5, pady=5)
entryBegin = tk.Entry(frame2, width=5)
entryBegin.pack(side=tk.LEFT, padx=0, expand=True)
frame3 = tk.Frame(self, bg="grey")
frame3.pack(fill=tk.BOTH, expand=True)
frame4 = tk.Frame(self)
frame4.pack(fill=tk.BOTH, expand=True)
startbutton = tk.Button(frame4, text="Start Clustering", height="100", width="100")
startbutton.pack(side=tk.RIGHT, padx=5, pady=5)
def main():
root = tk.Tk()
root.geometry("300x160+300+160")
app = Example(root)
root.mainloop()
if __name__ == '__main__':
main()
I did it here with the tkinter widgets. You can obviously do import tkinter.ttk as ttk and rewrite the code using those, it is just a matter of taste.

Categories

Resources