not recieving the textbox value in the function - python-3.x

'''
basically i am trying to make a textbox to take input from the user and opening with some default name and changing it to user given name in another textbox but the value of the textbox always is eter a none or empty string which raises an error
'''
`nweb=Toplevel()
nweb.configure(background='blue')
nweb.geometry('1366x768')
fram.destroy()
n1=Label(nweb,text='enter the following details:',font='Aerial 16',fg='yellow',bg='blue').grid(column=0,row=1)
n2=Label(nweb,text='DONGLE',font='Aerial 100',fg='yellow',bg='blue').grid(column=0,row=0)
n3=Label(nweb,text='website name:',font='Aerial 10',fg='yellow',bg='blue').grid(column=0,row=2)
edit = Text(nweb, width=50, height=1)
edit.grid(column=1,row=2)
n5=Label(nweb,text='keywords (write it in words as sentence):',font='Aerial 10',fg='yellow',bg='blue').grid(column=0,row=4)
edit2 = Text(nweb, width=50, height=1)
edit2.grid(column=1,row=4)
st=edit2
def getdetail():
def webcontent():
webcon=Toplevel()
webcon.geometry('1366x768')
webcon.configure(background='blue')
text = Text(webcon)
text.insert('1.0','ENTER YOUR WEBSITE CONTENT:')
text.pack(side=TOP,fill=BOTH,expand=1)
if text.get(1.0,END)!='':
with open('C:\\Users\\User\\OneDrive\\Desktop\\MUSTAFA\'S PROJECT FILES\\websites\\1234.dat','ab') as f1:
pickle.dump(text.get(1.0,END),f1)
os.rename('1234.dat',str(st))
err=False
try:
with open('search.dat','rb') as f1:
while True:
l=pickle.load(f1)
if l[0]==edit.get(1.0,END):
g=Label(nweb,text='webite already taken',fg='red',bg='blue').grid(column=0,row=6)
err=True
elif 'www.' not in edit.get(1.0,END) and '.com' not in edit.get(1.0,END) :
g=Label(nweb,text='inappropriate webite name',fg='red',bg='blue').grid(column=0,row=6)
err=True
except EOFError:
if not(err):
with open('search.dat','ab') as f1:
l=[edit.get(1.0,END),edit2.get(1.0,END)]
pickle.dump(l,f1)
edit.delete(1.0,END)
edit2.delete(1.0,END)
webcontent()
create=Button(nweb, text='enter' , command=getdetail, bg='yellow').grid(column=0,row=5)`
'''and i have tried everything from tkinter variables to python variables if u help me out it will be very kind of u'''

Related

InlineKeyboardMarkup Telegram bot (pyTelegramBotAPI)

I am making a bot on pyTelegramBotAPI, I need to generate a list of buttons and write it into the keyboard (So that there are 5 buttons in a row). How should I do it? I have a code:
def start(message):
markup = types.InlineKeyboardMarkup()
buttons = []
for i in range(-12, 15):
if i < 0:
button = types.InlineKeyboardButton(f'{i}', callback_data=f'{i}')
elif i == 0:
button = types.InlineKeyboardButton(f'±{i}', callback_data=f'{i}')
else:
button = types.InlineKeyboardButton(f'+{i}', callback_data=f'{i}')
buttons.append(button)
if len(buttons) == 5:
# here i want to add buttons in a row
bot.send_message(message.chat.id, f'Здравствуйте, <b>{message.from_user.first_name}</b>. Для начала необходимо настроить часовой пояс. Выберите разницу во времени относительно UTC (Москва: "+3", Владивосток: "+10", Исландия: "+1")', parse_mode='html', reply_markup=markup)```
I can advise you to create a separate module responsible for keyboards.
example of modules
This way you can separate the logic of handlers from the logic of keyboards.
As torrua wrote earlier, you can use the keyboa (how to use keyboa) library.
or write the functions yourself to create keyboards and buttons in it.
What you need to know for this:
telebot.types.InlineKeyboardMarkup() # creates an empty keyboard.
telebot.type.InlineKeyboardButton() # creates a button for the keyboard created earlier.
.row() # determines the position of the buttons in the keyboard.
example of function to get keyboards
You can do it easy with keyboa:
from keyboa import Keyboa
def start():
buttons = []
for i in range(-12, 15):
if i < 0:
button = (f'{i}', i)
elif i == 0:
button = (f'±{i}', i)
else:
button = (f'+{i}', i)
buttons.append(button)
keyboard = Keyboa(items=buttons, items_in_row=5).keyboard
bot.send_message(message.chat.id, f'Здравствуйте, <b>{message.from_user.first_name}</b>. Для начала необходимо настроить часовой пояс. Выберите разницу во времени относительно UTC (Москва: "+3", Владивосток: "+10", Исландия: "+1")', parse_mode='html', reply_markup=keyboard)```

How to Call a Function with 'on_press' command inside same class using KIVY button

I'm trying to call a popup and the have the user input text. After hitting the save button inside my popup it updates a new widget.
I have almost everything working but I don't know how to properly call a function inside the same class.
I have two functions inside of my
'class Trackers(Screen):'
how can I make a button that 'on_press' command will trigger another function?
The line of code I need to be fixed is this:
okay = Button(text='Save', on_press=self.addit(str(text_input), num), on_release=pop.dismiss)
Thank you so much.
''''
def addWidget(self):
num = '0'
box = BoxLayout(orientation= 'vertical', padding=40, spacing=5)
pop = Popup(title='Tracker: details', content=box, size_hint=(None,None), size=(300,300))
text_input = TextInput(hint_text='Add Trackers', multiline=False,)
okay = Button(text='Save', on_press=self.addit(str(text_input), num), on_release=pop.dismiss)
box.add_widget(text_input)
box.add_widget(okay)
pop.open()
def addit(self, text_input, num, *args):
if text_input not in self.storage.keys():
self.ids.track.add_widget(Tracker(text=text_input, number=num, data=self.storage))
self.storage[text_input] = '0'
text_input = ''
self.saveData()
else:
box = BoxLayout(orientation= 'vertical', padding=40, spacing=5)
pop = Popup(title=f'Opps: "{text_input}" is already listed below', content=box, size_hint=(None,None), size=(300,180))
try_again = Button(text='Try Again', on_release=pop.dismiss)
box.add_widget(try_again)
pop.open()
''''

Error using checkmouse

I'm trying to use checkmouse in order to undraw something from my window. When someone clicks the button it should undraw the text and write something else. I'm using checkMouse and getX() and getY() to do this but i keep receiving this error that states:
File "C:\Users\User\Documents\python\project2.py", line 71, in panel
if (clicknew.getX()>90 and clicknew.getX()<210) and (clicknew.getY()>35 and clicknew.getY() < 0):
AttributeError: 'NoneType' object has no attribute 'getX'
this code that i have done so far is as follows:
from graphics import *
#creating the game panel window
def panel():
#grey window, with coordinates flipped, with banners etc
win = GraphWin("Start Panel", 300,200)
win.setCoords(0,0,300,200)
win.setBackground("light grey")
#drawing the BoilerMazer banner with text
boilermazer = Rectangle(Point(0,200),Point(300,160))
boilermazer.setFill("white")
boilermazer.draw(win)
#text inside
banner1 = Text(Point(150,180),"BoilerMazer")
banner1.setStyle("bold")
banner1.setSize(20)
banner1.draw(win)
#initial game panel is going to have two buttons and a top scores object
#top score "screen"
toprec = Rectangle(Point(60,140),Point(240,50))
toprec.setFill("white")
toprec.draw(win)
#text inside toprec
topscores = Text(Point(150,130),"TOP SCORES")
topscores.setSize(8)
topscores.draw(win)
border = Text(Point(150,120),"======")
border.draw(win)
bigmac = Text(Point(150,110),"Big Mac 21")
bigmac.setSize(8)
bigmac.draw(win)
tt = Text(Point(150,90),"T.T 23")
tt.setSize(8)
tt.draw(win)
cshell = Text(Point(150,75),"C-Shell 25")
cshell.setSize(8)
cshell.draw(win)
macmac = Text(Point(150,55),"MacMac 27")
macmac.setSize(8)
macmac.draw(win)
#new player button that will eventually be clicked
new1 = Point(90,35)
new2 = Point(210,0)
newrec = Rectangle(new1,new2)
newrec.setFill("chartreuse2")
newrec.draw(win)
#new player button text
newplayer = Text(Point(150,18),"NEW PLAYER")
newplayer.draw(win)
#reset button
resetrec = Rectangle(Point(240,35),Point(300,0))
resetrec.setFill("red")
resetrec.draw(win)
#resettext
reset = Text(Point(270,18),"RESET")
reset.draw(win)
#secondary panel window is the game panel after they click new player
#set up points that we check between for the new player button first
#setting up the checkmouse
clicknew = win.checkMouse()
if (clicknew.getX()>90 and clicknew.getX()<210) and (clicknew.getY()>35 and clicknew.getY() < 0):
newplayer.undraw()
you can find the graphics window here:http://mcsp.wartburg.edu/zelle/python/graphics.py
I don't understand what I'm doing wrong, is there some other method that I'm supposed to be using? Thanks for your help
According to the docs, checkMouse() returns None if no mouse click has been detected priorly. So that seems to be the case.
You could put a loop around the call to checkMouse and keep checking if clicknew is not None and only in that case go on in your program. But maybe there's a better way...
UPDATE:
Example:
while True:
clicknew = win.getMouse()
if clicknew:
break
else:
time.sleep(0.1) # avoid busy waiting
# clicknew is set now => use it

python : bind function to button

this is my python code GUI generated from PAGE 4.6.
I want to create a function which will change the textbox value in real time example
tbCapturedImage.set("test 1").
take a look at
self.btnCapture.bind('<Button-1>', self.Capture_a)
but it cant seems to change the value of the textbox.
self.tbCapturedImage = Text(self.TLabelframe1)
self.tbCapturedImage.place(relx=0.04, rely=0.65, relheight=0.33
, relwidth=0.93)
self.tbCapturedImage.configure(background="white")
self.tbCapturedImage.configure(font="TkTextFont")
self.tbCapturedImage.configure(selectbackground="#c4c4c4")
self.tbCapturedImage.configure(width=206)
self.tbCapturedImage.configure(wrap=WORD)
self.btnCapture = Button(master)
self.btnCapture.place(relx=0.01, rely=0.92, height=45, width=982)
self.btnCapture.configure(activebackground="#d9d9d9")
self.btnCapture.configure(disabledforeground="#a7a4a7")
self.btnCapture.configure(font=font11)
self.btnCapture.configure(text='''Capture Image''')
self.btnCapture.bind('<Button-1>', self.Capture_a)
self.Labelframe1 = LabelFrame(master)
self.Labelframe1.place(relx=0.25, rely=0.48, relheight=0.43
, relwidth=0.74)
self.Labelframe1.configure(relief=GROOVE)
self.Labelframe1.configure(text='''Color Detection''')
self.Labelframe1.configure(width=740)
self.Labelframe2 = LabelFrame(master)
self.Labelframe2.place(relx=0.25, rely=0.05, relheight=0.43
, relwidth=0.35)
self.Labelframe2.configure(relief=GROOVE)
self.Labelframe2.configure(text='''Perspective Transformation''')
self.Labelframe2.configure(width=350)
self.Labelframe3 = LabelFrame(master)
self.Labelframe3.place(relx=0.61, rely=0.05, relheight=0.43
, relwidth=0.38)
self.Labelframe3.configure(relief=GROOVE)
self.Labelframe3.configure(text='''Haar-Like Detection''')
self.Labelframe3.configure(width=380)
def Capture():
tbCapture.Set("test")
def Capture_a(self,event):
self.Capture()
if __name__ == '__main__':
vp_start_gui()
You have to use self and set instead of Set
And probably you should use tbCapturedImage instead of tbCapture
def Capture(self): # self
self.tbCapturedImage.set("test") # self, set and tbCapturedImage
BTW: you can use command= in Button instead of bind
self.btnCapture = Button(master, command=self.Capture)
or
self.btnCapture.configure(command=self.Capture)
command= doesn't send event so method doesn't need argument event

a single tkinter button for multi function

I am trying to implement a single tkinter button which should "tail -f" some log file in a remote server. It should also stop the process locally AND kill the remote tail process when it is clicked for the second time. I tried this by not using tkinter with success.It stops when ctrl c is pressed.
When the tail(button3) button is clicked it hangs and it waits for the job completed. It is not accepting any new events until then. I know tkinter is single threaded and believe this is causing the issue. Code is below, appreciate any help.
from Tkinter import *
from re import *
import paramiko
import time
import select
class MyApp:
def __init__(self, parent):
self.myParent = parent
self.myContainer1 = Frame(parent,width=500,height=500)
self.myContainer1.pack()
#------------------ LABEL #1 for MAC ------------------------------------
#mac label field
self.label = Label (self.myContainer1, text='enter MAC').pack(side=TOP,padx=10,pady=10)
#------------------ ENTRY FIELD #1 for MAC ------------------------------------
#mac entry field
mac_var=StringVar()
self.entry = Entry(self.myContainer1,textvariable= mac_var ,width=10)
self.entry.pack(side=TOP,padx=100,pady=10)
mac_var.set("XXXXX")
s=mac_var.get()
#------------------ LABEL #2 for MAC OWNER ------------------------------------
#name label field
self.label = Label (self.myContainer1, text='enter MAC owner').pack(side=TOP,padx=10,pady=10)
#------------------ ENTRY #2 for MAC OWNER ------------------------------------
#name entry field
name_var=StringVar()
self.entry = Entry(self.myContainer1,textvariable= name_var ,width=25)
self.entry.pack(side=TOP,padx=100,pady=10)
name_var.set("name surname")
s=name_var.get()
#------------------ BUTTON #3 ------------------------------------
# event binding
self.button3 = Button(self.myContainer1)
self.button3.bind("<Button-1>", self.button3Click)
self.button3.configure(text="tail", background="purple")
self.button3.pack(side=LEFT)
def button3Click(self, event):
if self.button3["background"] == "purple":
self.button3.configure(text="Cancel Tail", background="yellow")
self.tail_flag=True
print "tail_flag is" , self.tail_flag
self.taillogg()
else:
self.button3.configure(text="Tail", background="purple")
self.canceltaillogg()
#root.destroy()
def canceltaillogg(self):
self.tail_flag=False
print "tail_flag is" , self.tail_flag
def taillogg(self):
server, port, username, password = ('myserver', 22, 'root', 'passw')
paramiko.util.log_to_file("C:\\log_transport_paramiko.txt")
nbytes = 100
trans = paramiko.Transport((server, port))
trans.connect(username = username, password = password)
trans.set_keepalive(1) # when ssh dies (with Ctrl C) processes spawned by that ssh connections will die, too ( in one sec)
sess = trans.open_channel("session")
#Once the channel is established, we can execute only one command.
#To execute another command, we need to create another channel
sess.exec_command('tail -f /usr/local/var/log/radius/radius.log')
timeout = 10
timestart =time.time()
while True:
try:
rl, wl, xl = select.select([sess],[],[],0.0)
if len(rl) > 0: #stdout
print sess.recv(1024)
if time.time()-timestart > timeout or self.tail_flag==False :
print "timeout 30 sec"
trans.close()
sess.close()
break
except KeyboardInterrupt :
print("Caught Control-C")
trans.close()
sess.close()
break
"""if self.tail_flag==False:
break"""
print ("\n")*100 # clear the screen
print "Starting program"
root = Tk()
root.title('MAC REGISTRATION APPLET')
myapp = MyApp(root)
print ("Ready to start executing the event loop.")
root.mainloop()
print ("Finished executing the event loop.")
Try this - see if it gives you the behavior your want.
self.button3.bind("<Button-1>", lambda:self.root.after(0, self.button3Click)
Also, this is unrelated, but you don't have to call "bind" on your button - it has a built in callback attribute called command:
self.button3 = Button(self.myContainer1, command=lambda:self.root.after(0, self.button3Click))
# self.button3.bind("<Button-1>", self.button3Click) (don't need this)
Then you'll want to remove the event argument from the button3Click function, since the button callback doesn't receive any arguments.

Resources