为什么在创建按钮命令时立即执行?
在 Tkinter 中,将命令分配给按钮可能会导致意外行为,其中该命令创建按钮后立即执行,而不是单击按钮时执行。这是因为命令选项的工作方式。
当您将命令参数指定为 Button(... command=button('hey')) 时,您实际上传递的是调用 button('嘿')到命令选项。这意味着按钮函数会立即执行,并将返回值分配给命令参数。
解决方案:传递对函数的引用
要避免这种情况问题,您需要传递对该函数的引用,而不是立即执行它。这可以使用 lambda 函数、functools.partial 或中间函数来完成。
使用 Lambda 函数
Lambda 函数提供了一种创建匿名函数的简单方法,该函数可以可以作为参考。例如:
b = Button(... command=lambda: button('hey'))
此 lambda 函数创建一个无名函数,调用时会使用参数“hey”执行按钮函数。然后可以将此引用传递给按钮的命令参数。
替代方法
- Functools.partial: 此函数允许您创建一个新函数,将参数部分应用于现有函数函数。
- 中间函数:您可以创建一个单独的函数,只需使用所需的参数包装按钮函数。
结论
通过传递对函数的引用而不是立即执行它,您可以确保按钮命令仅在按预期单击按钮。
以上是为什么我的 Tkinter 按钮立即执行命令而不是单击时执行命令?的详细内容。更多信息请关注PHP中文网其他相关文章!

Python是解释型语言,但也包含编译过程。1)Python代码先编译成字节码。2)字节码由Python虚拟机解释执行。3)这种混合机制使Python既灵活又高效,但执行速度不如完全编译型语言。

useeAforloopWheniteratingOveraseQuenceOrforAspecificnumberoftimes; useAwhiLeLoopWhenconTinuingUntilAcIntiment.ForloopSareIdeAlforkNownsences,而WhileLeleLeleLeleLoopSituationSituationSituationsItuationSuationSituationswithUndEtermentersitations。

pythonloopscanleadtoerrorslikeinfiniteloops,modifyingListsDuringteritation,逐个偏置,零indexingissues,andnestedloopineflinefficiencies

forloopsareadvantageousforknowniterations and sequests,供应模拟性和可读性;而LileLoopSareIdealFordyNamicConcitionSandunknowniterations,提供ControloperRoverTermination.1)forloopsareperfectForeTectForeTerToratingOrtratingRiteratingOrtratingRitterlistlistslists,callings conspass,calplace,cal,ofstrings ofstrings,orstrings,orstrings,orstrings ofcces

pythonisehybridmodelofcompilationand interpretation:1)thepythoninterspretercompilesourcececodeintoplatform- interpententbybytecode.2)thepytythonvirtualmachine(pvm)thenexecuteCutestestestesteSteSteSteSteSteSthisByTecode,BelancingEaseofuseWithPerformance。

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允许fordingfordforderynamictynamictymictymictymictyandrapiddefupment,尽管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

在您的知识之际,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations则youneedtoloopuntilaconditionismet

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond


热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

螳螂BT
Mantis是一个易于部署的基于Web的缺陷跟踪工具,用于帮助产品缺陷跟踪。它需要PHP、MySQL和一个Web服务器。请查看我们的演示和托管服务。

EditPlus 中文破解版
体积小,语法高亮,不支持代码提示功能

VSCode Windows 64位 下载
微软推出的免费、功能强大的一款IDE编辑器

ZendStudio 13.5.1 Mac
功能强大的PHP集成开发环境

PhpStorm Mac 版本
最新(2018.2.1 )专业的PHP集成开发工具